digitalkin
¤
DigitalKin SDK!
This package implements the DigitalKin agentic mesh standards.
Modules:
-
__version__–Version information.
-
community–Community integrations for DigitalKin.
-
core–Core of Digitlakin defining the task management and sub-modules.
-
grpc_servers–This package contains the gRPC server and client implementations.
-
logger–This module sets up a logger.
-
mixins–Mixin definitions.
-
models–This package contains the models for DigitalKin.
-
modules–Module package for DigitalKin.
-
services–This package contains the abstract base class for all services.
-
utils–General utils folder.
Classes:
-
ArchetypeModule–ArchetypeModule extends BaseModule to implement specific module types.
-
ModuleContext–ModuleContext provides a container for strategies and resources used by a module.
-
ModuleStatus–Possible module's state.
-
ServicesConfig–Service class describing the available services in a Module.
-
ToolModule–ToolModule extends BaseModule to implement specific module types.
-
TriggerHandler–Base class for all input-trigger handlers.
ArchetypeModule
¤
ArchetypeModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.ArchetypeModule[ArchetypeModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.ArchetypeModule
click digitalkin.ArchetypeModule href "" "digitalkin.ArchetypeModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ArchetypeModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
ModuleContext
¤
ModuleContext(
agent: AgentStrategy,
communication: CommunicationStrategy,
cost: CostStrategy,
filesystem: FilesystemStrategy,
identity: IdentityStrategy,
registry: RegistryStrategy,
snapshot: SnapshotStrategy,
storage: StorageStrategy,
task_manager: TaskManagerStrategy,
user_profile: UserProfileStrategy,
session: dict[str, Any],
metadata: dict[str, Any] | None = None,
helpers: dict[str, Any] | None = None,
callbacks: dict[str, Any] | None = None,
tool_cache: ToolCache | None = None,
request_metadata: dict[str, str] | None = None,
)
ModuleContext provides a container for strategies and resources used by a module.
This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.
Parameters:
-
(agent¤AgentStrategy) –AgentStrategy.
-
(communication¤CommunicationStrategy) –CommunicationStrategy.
-
(cost¤CostStrategy) –CostStrategy.
-
(filesystem¤FilesystemStrategy) –FilesystemStrategy.
-
(identity¤IdentityStrategy) –IdentityStrategy.
-
(registry¤RegistryStrategy) –RegistryStrategy.
-
(snapshot¤SnapshotStrategy) –SnapshotStrategy.
-
(storage¤StorageStrategy) –StorageStrategy.
-
(task_manager¤TaskManagerStrategy) –TaskManagerStrategy.
-
(user_profile¤UserProfileStrategy) –UserProfileStrategy.
-
(metadata¤dict[str, Any] | None, default:None) –dict defining differents Module metadata.
-
(helpers¤dict[str, Any] | None, default:None) –dict different user defined helpers.
-
(session¤dict[str, Any]) –dict referring the session IDs or informations.
-
(callbacks¤dict[str, Any] | None, default:None) –Functions allowing user to agent interaction.
-
(tool_cache¤ToolCache | None, default:None) –ToolCache with pre-resolved tool references from setup.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
-
digitalkin-
ArchetypeModule -
ToolModule -
TriggerHandler -
communityagno -
mixins-
AgUiMixinsend_message -
BaseMixin -
CostMixin -
FilesystemMixin -
LoggerMixin -
StorageMixin -
agui_mixinAgUiMixinsend_message -
base_mixinBaseMixin -
callback_mixinUserMessageMixinsend_message -
chat_history_mixinChatHistoryMixin -
cost_mixinCostMixin -
file_history_mixinFileHistoryMixin -
filesystem_mixinFilesystemMixin -
logger_mixinLoggerMixin -
storage_mixinStorageMixin
-
-
modules -
utilspackage_discoverModuleDiscovererinit_handlers
-
Methods:
-
cleanup–Close all service strategies and release their resources.
-
create_openai_style_tools–Create OpenAI-style function calling schemas for a tool module.
-
create_tool_functions–Create tool functions for all protocols in a tool setup.
-
get_module_schemas_by_id–Get module schemas by ID, discovering address/port from registry.
create_openai_style_tools
¤
Create OpenAI-style function calling schemas for a tool module.
Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.
Parameters:
Returns:
create_tool_functions
¤
create_tool_functions(
slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]
Create tool functions for all protocols in a tool setup.
Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.
This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.
Parameters:
Returns:
-
list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]–List of (ToolDefinition, async_generator_function) tuples. Empty if not found.
ModuleStatus
¤
flowchart TD
digitalkin.ModuleStatus[ModuleStatus]
click digitalkin.ModuleStatus href "" "digitalkin.ModuleStatus"
Possible module's state.
ServicesConfig
¤
ServicesConfig(
services_config_strategies: dict[str, ServicesStrategy | None] = {},
services_config_params: dict[str, dict[str, Any | None] | None] = {},
mode: ServicesMode = LOCAL,
**kwargs: dict[str, Any],
)
flowchart TD
digitalkin.ServicesConfig[ServicesConfig]
click digitalkin.ServicesConfig href "" "digitalkin.ServicesConfig"
Service class describing the available services in a Module.
This class manages the strategy implementations for various services, allowing them to be switched between local and remote modes.
Parameters:
-
(services_config_strategies¤dict[str, ServicesStrategy | None], default:{}) –Dictionary mapping service names to strategy implementations
-
(services_config_params¤dict[str, dict[str, Any | None] | None], default:{}) –Dictionary mapping service names to configuration parameters
-
(mode¤ServicesMode, default:LOCAL) –The mode of the services (local or remote)
-
(**kwargs¤dict[str, Any], default:{}) –Additional keyword arguments passed to the parent class constructor
Methods:
-
get_strategy_config–Get the configuration for a specific strategy.
-
init_strategy–Initialize a specific strategy.
-
update_mode–Update the strategy mode.
-
valid_strategy_names–Get the list of valid strategy names.
Attributes:
-
agent(type[AgentStrategy]) –Get the agent service strategy class based on the current mode.
-
communication(type[CommunicationStrategy]) –Get the communication service strategy class based on the current mode.
-
cost(type[CostStrategy]) –Get the cost service strategy class based on the current mode.
-
filesystem(type[FilesystemStrategy]) –Get the filesystem service strategy class based on the current mode.
-
identity(type[IdentityStrategy]) –Get the identity service strategy class based on the current mode.
-
registry(type[RegistryStrategy]) –Get the registry service strategy class based on the current mode.
-
snapshot(type[SnapshotStrategy]) –Get the snapshot service strategy class based on the current mode.
-
storage(type[StorageStrategy]) –Get the storage service strategy class based on the current mode.
-
task_manager(type[TaskManagerStrategy]) –Get the task_manager service strategy class based on the current mode.
-
user_profile(type[UserProfileStrategy]) –Get the user_profile service strategy class based on the current mode.
agent
property
¤
agent: type[AgentStrategy]
Get the agent service strategy class based on the current mode.
communication
property
¤
communication: type[CommunicationStrategy]
Get the communication service strategy class based on the current mode.
cost
property
¤
cost: type[CostStrategy]
Get the cost service strategy class based on the current mode.
filesystem
property
¤
filesystem: type[FilesystemStrategy]
Get the filesystem service strategy class based on the current mode.
identity
property
¤
identity: type[IdentityStrategy]
Get the identity service strategy class based on the current mode.
registry
property
¤
registry: type[RegistryStrategy]
Get the registry service strategy class based on the current mode.
snapshot
property
¤
snapshot: type[SnapshotStrategy]
Get the snapshot service strategy class based on the current mode.
storage
property
¤
storage: type[StorageStrategy]
Get the storage service strategy class based on the current mode.
task_manager
property
¤
task_manager: type[TaskManagerStrategy]
Get the task_manager service strategy class based on the current mode.
user_profile
property
¤
user_profile: type[UserProfileStrategy]
Get the user_profile service strategy class based on the current mode.
get_strategy_config
¤
init_strategy
¤
init_strategy(name: str, mission_id: str, setup_id: str, setup_version_id: str) -> Any
Initialize a specific strategy.
Parameters:
-
(name¤str) –The name of the strategy to initialize
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The setup ID for the strategy
-
(setup_version_id¤str) –The setup version ID for the strategy
Returns:
-
Any–The initialized strategy instance
Raises:
-
ValueError–If the strategy is not found
update_mode
¤
update_mode(mode: ServicesMode) -> None
Update the strategy mode.
Parameters:
-
(mode¤ServicesMode) –The new mode to use for all strategies
ToolModule
¤
ToolModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.ToolModule[ToolModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.ToolModule
click digitalkin.ToolModule href "" "digitalkin.ToolModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ToolModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
TriggerHandler
¤
TriggerHandler(context: ModuleContext)
flowchart TD
digitalkin.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.TriggerHandler href "" "digitalkin.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Base class for all input-trigger handlers.
Each handler declares
- protocol_key: the Literal value this handler processes
- handle(): logic to process the validated payload
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Asynchronously processes the input data specific to Handler and streams results via the provided callback.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
abstractmethod
async
¤
handle(
input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None
Asynchronously processes the input data specific to Handler and streams results via the provided callback.
Parameters:
-
(input_data¤InputModelT) –The input data to be processed by the handler.
-
(setup_data¤SetupModelT) –The setup or configuration data required for processing.
-
(context¤ModuleContext) –The context object containing module-specific information and resources.
Returns:
-
Any(None) –The result of the processing, if applicable.
Note
self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])
The callback must be awaited to ensure results are streamed correctly during processing.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
__version__
¤
Version information.
community
¤
Community integrations for DigitalKin.
This package contains community-contributed integrations with various AI frameworks and tools (Agno, LangChain, etc.).
Modules:
-
agno–Agno framework integration for DigitalKin.
agno
¤
Agno framework integration for DigitalKin.
Adapters, converters, and HITL helpers for building DigitalKin modules on top of the Agno agent framework. Exports:
- :class:
AgnoStreamAdapter— Agno streaming events → DigitalKin events. - :func:
agui_tool_to_external_function/ :func:make_tools_factory— register AG-UI client-side (frontend) tools as Agno external Functions. - :class:
AgnoHitlRunner, :class:PausedRunStore, :class:PauseInfo, :class:PausedRunRecord, :data:HITL_STORAGE_CONFIG, :func:emit_awaiting_tool_result— human-in-the-loop (HITL) runner that persists a paused Agno run via the module's :class:~digitalkin.services.storage.StorageStrategyand resumes it when the front replies with aToolMessage.
Modules:
-
agno_adapter–Adapter to convert Agno events to DigitalKin framework-agnostic events.
-
agui_tools–AG-UI frontend tools → Agno external Functions.
-
hitl–Human-in-the-loop (HITL) runner for Agno agents with AG-UI frontend tools.
Classes:
-
AgnoHitlRunner–High-level runner for an Agno agent with AG-UI frontend-tool support.
-
AgnoStreamAdapter–Stateful converter: Agno streaming events -> DigitalKin events.
-
PauseInfo–Summary of a paused Agno run.
-
PausedRunRecord–Persistent snapshot of an Agno run paused on external tool execution.
-
PausedRunStore–Thin wrapper around :class:
StorageStrategyfor thepaused_runscollection.
Functions:
-
agui_tool_to_external_function–Wrap an AG-UI tool definition as an Agno external
Function. -
emit_awaiting_tool_result–Emit an AG-UI
RunFinishedwithstatus="awaiting_tool_result". -
emit_messages_snapshot–Emit an AG-UI
MessagesSnapshotevent. -
make_tools_factory–Build an Agno
toolsfactory that merges base tools with per-run AG-UI tools.
Attributes:
-
HITL_STORAGE_CONFIG(dict[str, type[BaseModel]]) –Drop-in storage config fragment — merge into your module's
services_config_params.
HITL_STORAGE_CONFIG
module-attribute
¤
HITL_STORAGE_CONFIG: dict[str, type[BaseModel]] = {
_PAUSED_RUNS_COLLECTION: PausedRunRecord
}
Drop-in storage config fragment — merge into your module's services_config_params.
Example::
services_config_params = {
"storage": {
"config": {**HITL_STORAGE_CONFIG, "my_other_collection": MyModel},
...
},
}
AgnoHitlRunner
¤
AgnoHitlRunner(
*,
agent: Agent,
storage: StorageStrategy | None = None,
store: PausedRunStore | None = None,
dependency_key: str = "agui_tools",
)
High-level runner for an Agno agent with AG-UI frontend-tool support.
Wraps a configured :class:~agno.agent.Agent and a
:class:PausedRunStore, and exposes three levels of API:
- :meth:
run/ :meth:continue_paused_run— low-level: stream one Agno run (fresh or resumed) and return a :class:PauseInfoif it paused on an external tool. - :meth:
try_resume— inspects an AG-UI input and resumes iff a matching :class:~ag_ui.core.types.ToolMessageis present. - :meth:
handle_agui_input— all-in-one: detects resume vs fresh message, dispatches, and (optionally) emits the awaitingRunFinishedevent on pause. Use this one from a trigger.
Parameters:
-
(agent¤Agent) –The Agno agent. It must be built with
tools=make_tools_factory(base_tools)andcache_callables=False— otherwise the frontend tools injected per-run won't reach the LLM. -
(storage¤StorageStrategy | None, default:None) –Convenience: if provided and
storeis not, a :class:PausedRunStoreis constructed automatically. -
(store¤PausedRunStore | None, default:None) –Pre-built paused-run store. Wins over
storage. -
(dependency_key¤str, default:'agui_tools') –The Agno
dependencieskey under which the runner passes the per-run AG-UI tool list. Must match the key used by :func:make_tools_factory. Defaults to"agui_tools".
Raises:
-
ValueError–If neither
storagenorstoreis provided.
Methods:
-
continue_paused_run–Resume a previously paused run.
-
handle_agui_input–One-shot dispatch of an AG-UI
RunAgentInput. -
run–Stream a fresh Agno run.
-
try_resume–Try to resume a paused run from an AG-UI input.
continue_paused_run
async
¤
continue_paused_run(
thread_id: str,
tool_results: dict[str, str],
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
run_id: str | None = None,
agui_tools: list[Tool] | None = None,
) -> PauseInfo | None
Resume a previously paused run.
Loads the persisted :class:~agno.run.agent.RunOutput, injects
the tool results into the matching
:class:~agno.run.requirement.RunRequirement entries, and calls
:meth:~agno.agent.Agent.acontinue_run. On normal completion the
storage record is removed; on re-pause it is refreshed.
Parameters:
-
(thread_id¤str) –AG-UI thread identifier (the storage key).
-
(tool_results¤dict[str, str]) –Mapping of
tool_call_id→ serialized result (typically a JSON string). Every pending tool must be resolved — unresolved requirements will stall the run. -
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Digitalkin-event callback (same contract as :meth:
run). -
(run_id¤str | None, default:None) –AG-UI run identifier for this resume turn. Used to emit a synthetic
RUN_STARTEDbefore streaming — Agno emitsRunContinued(notRunStarted) on resume. -
(agui_tools¤list[Tool] | None, default:None) –Frontend tool definitions for the resumed run. The AG-UI client should re-send the same list it provided at the original turn so tool schemas stay registered.
Returns:
handle_agui_input
async
¤
handle_agui_input(
input_data: Any,
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
context: ModuleContext | None = None,
message: str | None = None,
images: list[Any] | None = None,
) -> PauseInfo | None
One-shot dispatch of an AG-UI RunAgentInput.
Handles the three cases in order:
- Resume a paused run if the input carries a matching
ToolMessage(see :meth:try_resume). - Drop a stale paused record if the input is a new
UserMessagewhile a tool was pending (HITL abandon). - Fresh run on the last
UserMessageininput_data.messages(or on the explicitmessageargument).
When a run pauses (fresh or resumed) and context is provided,
this method also emits the AG-UI RunFinished with
status="awaiting_tool_result" via
:func:emit_awaiting_tool_result. Pass context=None if you
want to emit it yourself.
Parameters:
-
(input_data¤Any) –Any object with
thread_id,messages, andtoolsattributes (typically anAgUiStreamInput). -
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Digitalkin-event callback (e.g. wrapping
self.send_message(context, event)in a trigger). -
(context¤ModuleContext | None, default:None) –If provided, the awaiting
RunFinishedis emitted automatically on pause. -
(message¤str | None, default:None) –Override the user prompt extraction. Normally left as
None— the runner picks the lastUserMessagecontent frominput_data.messages. -
(images¤list[Any] | None, default:None) –Optional multimodal inputs forwarded to Agno.
Returns:
run
async
¤
run(
message: str,
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
thread_id: str,
agui_tools: list[Tool] | None = None,
images: list[Any] | None = None,
) -> PauseInfo | None
Stream a fresh Agno run.
Parameters:
-
(message¤str) –User prompt to send to the agent.
-
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Async callback invoked for each digitalkin event produced by :class:
AgnoStreamAdapter. Typically maps through :meth:AgUiMixin.send_message. -
(thread_id¤str) –AG-UI thread identifier (used as the paused-run storage key if the run pauses).
-
(agui_tools¤list[Tool] | None, default:None) –Frontend tools declared by the AG-UI client for this run. Merged with the agent's base tools through the factory;
Noneor empty is equivalent to "no frontend tools this turn". -
(images¤list[Any] | None, default:None) –Optional multimodal inputs forwarded to Agno.
Returns:
-
PauseInfo | None–Noneon normal completion. A :class:PauseInfoif the run -
PauseInfo | None–paused on one or more external tool calls — the caller is
-
PauseInfo | None–responsible for emitting the awaiting
RunFinished(use -
PauseInfo | None–func:
emit_awaiting_tool_resultor let -
PauseInfo | None–meth:
handle_agui_inputdo it).
try_resume
async
¤
try_resume(
input_data: Any, *, send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]
) -> tuple[bool, PauseInfo | None]
Try to resume a paused run from an AG-UI input.
The input_data only needs to duck-type thread_id,
messages, and tools (typically an AgUiStreamInput).
This method:
- Loads the paused record for
input_data.thread_id. Returns(False, None)if there is none. - Looks for
ToolMessageentries ininput_data.messageswhosetool_call_idmatches a pending one. - If any match → dispatches :meth:
continue_paused_runand returns(True, pause_info_or_none). - If no match but the last message is a fresh
UserMessage, drops the stale record (HITL abandon) and returns(False, None).
Returns:
AgnoStreamAdapter
¤
AgnoStreamAdapter()
Stateful converter: Agno streaming events -> DigitalKin events.
Tracks reasoning and content state so that events arriving on
RunEvent.run_content are automatically wrapped in proper
lifecycle events (TextMessageStarted/Completed, ReasoningStarted/Completed).
Usage::
adapter = AgnoStreamAdapter()
async for raw_event in agent.arun(..., stream=True, stream_events=True):
for event in adapter.to_digitalkin_events(raw_event):
await send(event)
for event in adapter.flush():
await send(event)
Methods:
-
flush–Emit closing events for any active sequences at end of stream.
-
to_digitalkin_events–Convert one Agno event into one or more DigitalKin events.
Attributes:
-
is_paused(bool) –Whether the last stream ended on a run_paused event (external tool HITL).
-
paused_requirements(list[Any]) –Agno
RunRequirementobjects carried by the paused run. -
paused_tool_executions(list[Any]) –Agno
ToolExecutionobjects awaiting external execution (HITL).
is_paused
property
¤
is_paused: bool
Whether the last stream ended on a run_paused event (external tool HITL).
paused_requirements
property
¤
Agno RunRequirement objects carried by the paused run.
paused_tool_executions
property
¤
Agno ToolExecution objects awaiting external execution (HITL).
flush
¤
flush() -> list[BaseAgentRunEvent]
Emit closing events for any active sequences at end of stream.
Returns:
-
list[BaseAgentRunEvent]–List of closing events (empty if nothing is active).
to_digitalkin_events
¤
to_digitalkin_events(agno_event: AgnoRunEvent) -> list[BaseAgentRunEvent]
Convert one Agno event into one or more DigitalKin events.
Parameters:
-
(agno_event¤AgnoRunEvent) –Event from Agno's streaming API.
Returns:
-
list[BaseAgentRunEvent]–List of corresponding DigitalKin events (may be empty).
Raises:
-
ImportError–If the optional 'agno' dependency is not installed.
PauseInfo
dataclass
¤
PauseInfo(
thread_id: str,
run_id: str,
pending_tool_call_ids: list[str],
new_messages: list[Message] = list(),
)
Summary of a paused Agno run.
Returned by :meth:AgnoHitlRunner.run and related methods whenever
the run paused on one or more external tool calls. Callers typically
use it to emit the AG-UI awaiting-tool-result event to the front.
new_messages carries the AG-UI messages generated by Agno during
the paused run (user echoes, the assistant message with tool_calls,
and any tool results emitted before the pause). It's provided because
Agno does not emit stream events from which the front can reconstruct
the assistant-with-tool-calls message — in particular, when the LLM
goes straight from reasoning to a frontend tool call without emitting
any text. Consumers typically push these messages to the front via a
:class:~ag_ui.core.events.MessagesSnapshotEvent so the client has an
authoritative view of the conversation.
PausedRunRecord
¤
flowchart TD
digitalkin.community.agno.PausedRunRecord[PausedRunRecord]
click digitalkin.community.agno.PausedRunRecord href "" "digitalkin.community.agno.PausedRunRecord"
Persistent snapshot of an Agno run paused on external tool execution.
Stored in the paused_runs collection keyed by thread_id. The
payload field holds RunOutput.to_dict() verbatim so
:meth:agno.run.agent.RunOutput.from_dict can round-trip the run on
any replica when the front replies with the tool result(s).
PausedRunStore
¤
PausedRunStore(storage: StorageStrategy)
Thin wrapper around :class:StorageStrategy for the paused_runs collection.
Owns serialization of :class:~agno.run.agent.RunOutput and keying by
thread_id. Instances are cheap — create one per trigger handler.
Parameters:
-
(storage¤StorageStrategy) –The module's storage strategy. The collection
paused_runsmust be registered with :class:PausedRunRecord— use :data:HITL_STORAGE_CONFIG.
Methods:
-
delete–Remove the paused run record for a thread.
-
load–Fetch the paused run record for a thread.
-
save–Serialize and store a paused
RunOutput.
load
async
¤
load(thread_id: str) -> PausedRunRecord | None
Fetch the paused run record for a thread.
Parameters:
Returns:
-
The(PausedRunRecord | None) –class:
PausedRunRecordif one exists, otherwiseNone.
save
async
¤
save(run_output: RunOutput, thread_id: str) -> PauseInfo
agui_tool_to_external_function
¤
agui_tool_to_external_function(tool: Tool) -> Function
Wrap an AG-UI tool definition as an Agno external Function.
The resulting :class:Function carries the AG-UI schema as-is (Agno
accepts raw JSON Schema via parameters) and is marked with
external_execution=True so Agno emits the tool-call events but
skips the entrypoint and pauses the run when the LLM invokes it.
Parameters:
-
(tool¤Tool) –An :class:
ag_ui.core.types.ToolfromRunAgentInput.tools.
Returns:
-
An(Function) –class:
agno.tools.function.Functionready to be plugged into -
Function–an Agno agent's tool list.
emit_awaiting_tool_result
async
¤
emit_awaiting_tool_result(
context: ModuleContext,
*,
thread_id: str,
run_id: str,
pending_tool_call_ids: list[str],
) -> None
Emit an AG-UI RunFinished with status="awaiting_tool_result".
This is the protocol signal telling the front "the run paused on a
client-side tool; execute it and reply with a ToolMessage". It
goes out via context.callbacks.send_message (bypassing the
standard :class:~digitalkin.mixins.agui_mixin.AgUiMixin event
mapping, which has no notion of an "awaiting" status).
Parameters:
-
(context¤ModuleContext) –Current module context.
-
(thread_id¤str) –AG-UI thread identifier.
-
(run_id¤str) –Run identifier to echo back in the finished event.
-
(pending_tool_call_ids¤list[str]) –The
tool_call_idvalues the front must execute and resolve — echoed inresult.pending_tool_call_idsso the front can match them.
emit_messages_snapshot
async
¤
emit_messages_snapshot(context: ModuleContext, messages: list[Message]) -> None
Emit an AG-UI MessagesSnapshot event.
Typically called just before :func:emit_awaiting_tool_result on a
paused run so the front has an authoritative view of the conversation
(including the assistant message carrying the frontend tool_calls,
which cannot be reconstructed from the streamed tool-call events alone).
Parameters:
-
(context¤ModuleContext) –Current module context.
-
(messages¤list[Message]) –List of AG-UI messages, typically produced by :func:
_agno_messages_to_aguifromRunOutput.messages.
make_tools_factory
¤
make_tools_factory(
base_tools: list[Any], dependency_key: str = _DEFAULT_DEPENDENCY_KEY
) -> Callable[[RunContext], list[Any]]
Build an Agno tools factory that merges base tools with per-run AG-UI tools.
The returned callable is the value you pass to Agent(tools=...). On
every run, Agno resolves the factory with the current
:class:~agno.run.base.RunContext (see
:func:agno.utils.callables.aresolve_callable_tools). The factory
reads run_context.dependencies[dependency_key] — the list of
:class:~ag_ui.core.types.Tool you passed via
agent.arun(dependencies={dependency_key: [...]}) — converts them to
external :class:Function objects, and concatenates them with the
base_tools.
Parameters:
-
(base_tools¤list[Any]) –Toolkits / Functions always available to the agent (e.g.
AsyncDuckDuckGoTools()). Passed through unchanged. -
(dependency_key¤str, default:_DEFAULT_DEPENDENCY_KEY) –The key in
run_context.dependenciesunder which the caller places the per-run AG-UI tool list. Defaults to"agui_tools".
Returns:
agno_adapter
¤
Adapter to convert Agno events to DigitalKin framework-agnostic events.
This adapter bridges Agno-specific events to the DigitalKin event model, allowing the core DigitalKin SDK to remain independent of Agno.
The adapter owns ALL state management: tracking reasoning/content lifecycle, generating message_id and reasoning_id on each phase start, and emitting proper start/completed events for text message and reasoning sequences.
Classes:
-
AgnoStreamAdapter–Stateful converter: Agno streaming events -> DigitalKin events.
AgnoStreamAdapter
¤
AgnoStreamAdapter()
Stateful converter: Agno streaming events -> DigitalKin events.
Tracks reasoning and content state so that events arriving on
RunEvent.run_content are automatically wrapped in proper
lifecycle events (TextMessageStarted/Completed, ReasoningStarted/Completed).
Usage::
adapter = AgnoStreamAdapter()
async for raw_event in agent.arun(..., stream=True, stream_events=True):
for event in adapter.to_digitalkin_events(raw_event):
await send(event)
for event in adapter.flush():
await send(event)
Methods:
-
flush–Emit closing events for any active sequences at end of stream.
-
to_digitalkin_events–Convert one Agno event into one or more DigitalKin events.
Attributes:
-
is_paused(bool) –Whether the last stream ended on a run_paused event (external tool HITL).
-
paused_requirements(list[Any]) –Agno
RunRequirementobjects carried by the paused run. -
paused_tool_executions(list[Any]) –Agno
ToolExecutionobjects awaiting external execution (HITL).
is_paused
property
¤
is_paused: bool
Whether the last stream ended on a run_paused event (external tool HITL).
paused_requirements
property
¤
Agno RunRequirement objects carried by the paused run.
paused_tool_executions
property
¤
Agno ToolExecution objects awaiting external execution (HITL).
flush
¤
flush() -> list[BaseAgentRunEvent]
Emit closing events for any active sequences at end of stream.
Returns:
-
list[BaseAgentRunEvent]–List of closing events (empty if nothing is active).
to_digitalkin_events
¤
to_digitalkin_events(agno_event: AgnoRunEvent) -> list[BaseAgentRunEvent]
Convert one Agno event into one or more DigitalKin events.
Parameters:
-
(agno_event¤AgnoRunEvent) –Event from Agno's streaming API.
Returns:
-
list[BaseAgentRunEvent]–List of corresponding DigitalKin events (may be empty).
Raises:
-
ImportError–If the optional 'agno' dependency is not installed.
agui_tools
¤
AG-UI frontend tools → Agno external Functions.
The AG-UI protocol lets the client declare its own tools in
RunAgentInput.tools. Those tools are meant to be executed on the
frontend (a UI widget, a browser-local API call, a user prompt, …) rather
than by the agent process. This module provides the glue to expose them
to an Agno :class:~agno.agent.Agent as regular :class:~agno.tools.function.Function
objects marked with external_execution=True: when the LLM "calls" one,
Agno pauses the run (via :class:~agno.run.agent.RunPausedEvent) instead
of executing an entrypoint — letting the caller stream the tool-call
events to the front and resume later via :meth:~agno.agent.Agent.acontinue_run.
Usage::
from digitalkin.community.agno import make_tools_factory
from agno.agent import Agent
agent = Agent(
tools=make_tools_factory([AsyncDuckDuckGoTools()]),
cache_callables=False, # critical — see make_tools_factory
...
)
async for ev in agent.arun(
message,
dependencies={"agui_tools": input_data.tools},
stream=True,
stream_events=True,
):
...
Notes
dependencies is Agno's standard per-run injection bus. We use it
as a transport channel to hand the frontend tools to the tools
factory on every run — the tools themselves are actually registered
through the tools=factory mechanism, not through dependencies.
cache_callables=False is required so the factory is re-invoked on
each run (otherwise the first resolved tool list is cached forever and
subsequent requests would not see new frontend tools).
Functions:
-
agui_tool_to_external_function–Wrap an AG-UI tool definition as an Agno external
Function. -
make_tools_factory–Build an Agno
toolsfactory that merges base tools with per-run AG-UI tools.
agui_tool_to_external_function
¤
agui_tool_to_external_function(tool: Tool) -> Function
Wrap an AG-UI tool definition as an Agno external Function.
The resulting :class:Function carries the AG-UI schema as-is (Agno
accepts raw JSON Schema via parameters) and is marked with
external_execution=True so Agno emits the tool-call events but
skips the entrypoint and pauses the run when the LLM invokes it.
Parameters:
-
(tool¤Tool) –An :class:
ag_ui.core.types.ToolfromRunAgentInput.tools.
Returns:
-
An(Function) –class:
agno.tools.function.Functionready to be plugged into -
Function–an Agno agent's tool list.
make_tools_factory
¤
make_tools_factory(
base_tools: list[Any], dependency_key: str = _DEFAULT_DEPENDENCY_KEY
) -> Callable[[RunContext], list[Any]]
Build an Agno tools factory that merges base tools with per-run AG-UI tools.
The returned callable is the value you pass to Agent(tools=...). On
every run, Agno resolves the factory with the current
:class:~agno.run.base.RunContext (see
:func:agno.utils.callables.aresolve_callable_tools). The factory
reads run_context.dependencies[dependency_key] — the list of
:class:~ag_ui.core.types.Tool you passed via
agent.arun(dependencies={dependency_key: [...]}) — converts them to
external :class:Function objects, and concatenates them with the
base_tools.
Parameters:
-
(base_tools¤list[Any]) –Toolkits / Functions always available to the agent (e.g.
AsyncDuckDuckGoTools()). Passed through unchanged. -
(dependency_key¤str, default:_DEFAULT_DEPENDENCY_KEY) –The key in
run_context.dependenciesunder which the caller places the per-run AG-UI tool list. Defaults to"agui_tools".
Returns:
hitl
¤
Human-in-the-loop (HITL) runner for Agno agents with AG-UI frontend tools.
This module provides the high-level glue to build an Agno-powered module that supports AG-UI frontend tools — tools declared by the AG-UI client and executed on the front rather than on the agent process. The flow is:
- The front sends
RunAgentInputwith atoolslist. - The LLM calls one of those tools.
- Agno emits
RunPausedEvent(its HITL signal) and freezes the run. - We persist the paused :class:
~agno.run.agent.RunOutputvia the module's :class:~digitalkin.services.storage.StorageStrategy, keyed bythread_id. - We emit an AG-UI
RunFinishedwithresult={"status": "awaiting_tool_result", "pending_tool_call_ids": [...]}so the front knows to execute the tool and reply. - On the next
RunAgentInputcarrying a matchingToolMessage, we load the paused run, inject the result into the corresponding :class:~agno.run.requirement.RunRequirement, and resume via :meth:~agno.agent.Agent.acontinue_run.
The design keeps the process stateless (every replica can resume any thread) because all the state lives in the storage service.
Typical usage inside a module trigger::
from digitalkin.community.agno import (
AgnoHitlRunner,
HITL_STORAGE_CONFIG,
make_tools_factory,
)
# In your Module class — register the storage schema
services_config_params = {
"storage": {
"config": {
**HITL_STORAGE_CONFIG,
"agno_sessions": AgnoSession,
...
},
...
},
...
}
# In your agent factory
agent = Agent(
tools=make_tools_factory([MyBaseToolkit()]),
cache_callables=False,
...
)
# In your trigger handler
runner = AgnoHitlRunner(agent=agent, storage=context.storage)
pause_info = await runner.handle_agui_input(
input_data=input_data,
send=send,
context=context, # enables auto-emission of awaiting RunFinished
)
handle_agui_input will figure out whether this is a fresh user
message, a resume of a paused run, or an abandon (new user message while
a tool was pending) and dispatch accordingly.
Classes:
-
AgnoHitlRunner–High-level runner for an Agno agent with AG-UI frontend-tool support.
-
PauseInfo–Summary of a paused Agno run.
-
PausedRunRecord–Persistent snapshot of an Agno run paused on external tool execution.
-
PausedRunStore–Thin wrapper around :class:
StorageStrategyfor thepaused_runscollection.
Functions:
-
emit_awaiting_tool_result–Emit an AG-UI
RunFinishedwithstatus="awaiting_tool_result". -
emit_messages_snapshot–Emit an AG-UI
MessagesSnapshotevent.
Attributes:
-
HITL_STORAGE_CONFIG(dict[str, type[BaseModel]]) –Drop-in storage config fragment — merge into your module's
services_config_params.
HITL_STORAGE_CONFIG
module-attribute
¤
HITL_STORAGE_CONFIG: dict[str, type[BaseModel]] = {
_PAUSED_RUNS_COLLECTION: PausedRunRecord
}
Drop-in storage config fragment — merge into your module's services_config_params.
Example::
services_config_params = {
"storage": {
"config": {**HITL_STORAGE_CONFIG, "my_other_collection": MyModel},
...
},
}
AgnoHitlRunner
¤
AgnoHitlRunner(
*,
agent: Agent,
storage: StorageStrategy | None = None,
store: PausedRunStore | None = None,
dependency_key: str = "agui_tools",
)
High-level runner for an Agno agent with AG-UI frontend-tool support.
Wraps a configured :class:~agno.agent.Agent and a
:class:PausedRunStore, and exposes three levels of API:
- :meth:
run/ :meth:continue_paused_run— low-level: stream one Agno run (fresh or resumed) and return a :class:PauseInfoif it paused on an external tool. - :meth:
try_resume— inspects an AG-UI input and resumes iff a matching :class:~ag_ui.core.types.ToolMessageis present. - :meth:
handle_agui_input— all-in-one: detects resume vs fresh message, dispatches, and (optionally) emits the awaitingRunFinishedevent on pause. Use this one from a trigger.
Parameters:
-
(agent¤Agent) –The Agno agent. It must be built with
tools=make_tools_factory(base_tools)andcache_callables=False— otherwise the frontend tools injected per-run won't reach the LLM. -
(storage¤StorageStrategy | None, default:None) –Convenience: if provided and
storeis not, a :class:PausedRunStoreis constructed automatically. -
(store¤PausedRunStore | None, default:None) –Pre-built paused-run store. Wins over
storage. -
(dependency_key¤str, default:'agui_tools') –The Agno
dependencieskey under which the runner passes the per-run AG-UI tool list. Must match the key used by :func:make_tools_factory. Defaults to"agui_tools".
Raises:
-
ValueError–If neither
storagenorstoreis provided.
Methods:
-
continue_paused_run–Resume a previously paused run.
-
handle_agui_input–One-shot dispatch of an AG-UI
RunAgentInput. -
run–Stream a fresh Agno run.
-
try_resume–Try to resume a paused run from an AG-UI input.
continue_paused_run
async
¤
continue_paused_run(
thread_id: str,
tool_results: dict[str, str],
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
run_id: str | None = None,
agui_tools: list[Tool] | None = None,
) -> PauseInfo | None
Resume a previously paused run.
Loads the persisted :class:~agno.run.agent.RunOutput, injects
the tool results into the matching
:class:~agno.run.requirement.RunRequirement entries, and calls
:meth:~agno.agent.Agent.acontinue_run. On normal completion the
storage record is removed; on re-pause it is refreshed.
Parameters:
-
(thread_id¤str) –AG-UI thread identifier (the storage key).
-
(tool_results¤dict[str, str]) –Mapping of
tool_call_id→ serialized result (typically a JSON string). Every pending tool must be resolved — unresolved requirements will stall the run. -
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Digitalkin-event callback (same contract as :meth:
run). -
(run_id¤str | None, default:None) –AG-UI run identifier for this resume turn. Used to emit a synthetic
RUN_STARTEDbefore streaming — Agno emitsRunContinued(notRunStarted) on resume. -
(agui_tools¤list[Tool] | None, default:None) –Frontend tool definitions for the resumed run. The AG-UI client should re-send the same list it provided at the original turn so tool schemas stay registered.
Returns:
handle_agui_input
async
¤
handle_agui_input(
input_data: Any,
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
context: ModuleContext | None = None,
message: str | None = None,
images: list[Any] | None = None,
) -> PauseInfo | None
One-shot dispatch of an AG-UI RunAgentInput.
Handles the three cases in order:
- Resume a paused run if the input carries a matching
ToolMessage(see :meth:try_resume). - Drop a stale paused record if the input is a new
UserMessagewhile a tool was pending (HITL abandon). - Fresh run on the last
UserMessageininput_data.messages(or on the explicitmessageargument).
When a run pauses (fresh or resumed) and context is provided,
this method also emits the AG-UI RunFinished with
status="awaiting_tool_result" via
:func:emit_awaiting_tool_result. Pass context=None if you
want to emit it yourself.
Parameters:
-
(input_data¤Any) –Any object with
thread_id,messages, andtoolsattributes (typically anAgUiStreamInput). -
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Digitalkin-event callback (e.g. wrapping
self.send_message(context, event)in a trigger). -
(context¤ModuleContext | None, default:None) –If provided, the awaiting
RunFinishedis emitted automatically on pause. -
(message¤str | None, default:None) –Override the user prompt extraction. Normally left as
None— the runner picks the lastUserMessagecontent frominput_data.messages. -
(images¤list[Any] | None, default:None) –Optional multimodal inputs forwarded to Agno.
Returns:
run
async
¤
run(
message: str,
*,
send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]],
thread_id: str,
agui_tools: list[Tool] | None = None,
images: list[Any] | None = None,
) -> PauseInfo | None
Stream a fresh Agno run.
Parameters:
-
(message¤str) –User prompt to send to the agent.
-
(send¤Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]) –Async callback invoked for each digitalkin event produced by :class:
AgnoStreamAdapter. Typically maps through :meth:AgUiMixin.send_message. -
(thread_id¤str) –AG-UI thread identifier (used as the paused-run storage key if the run pauses).
-
(agui_tools¤list[Tool] | None, default:None) –Frontend tools declared by the AG-UI client for this run. Merged with the agent's base tools through the factory;
Noneor empty is equivalent to "no frontend tools this turn". -
(images¤list[Any] | None, default:None) –Optional multimodal inputs forwarded to Agno.
Returns:
-
PauseInfo | None–Noneon normal completion. A :class:PauseInfoif the run -
PauseInfo | None–paused on one or more external tool calls — the caller is
-
PauseInfo | None–responsible for emitting the awaiting
RunFinished(use -
PauseInfo | None–func:
emit_awaiting_tool_resultor let -
PauseInfo | None–meth:
handle_agui_inputdo it).
try_resume
async
¤
try_resume(
input_data: Any, *, send: Callable[[BaseAgentRunEvent], Coroutine[Any, Any, None]]
) -> tuple[bool, PauseInfo | None]
Try to resume a paused run from an AG-UI input.
The input_data only needs to duck-type thread_id,
messages, and tools (typically an AgUiStreamInput).
This method:
- Loads the paused record for
input_data.thread_id. Returns(False, None)if there is none. - Looks for
ToolMessageentries ininput_data.messageswhosetool_call_idmatches a pending one. - If any match → dispatches :meth:
continue_paused_runand returns(True, pause_info_or_none). - If no match but the last message is a fresh
UserMessage, drops the stale record (HITL abandon) and returns(False, None).
Returns:
PauseInfo
dataclass
¤
PauseInfo(
thread_id: str,
run_id: str,
pending_tool_call_ids: list[str],
new_messages: list[Message] = list(),
)
Summary of a paused Agno run.
Returned by :meth:AgnoHitlRunner.run and related methods whenever
the run paused on one or more external tool calls. Callers typically
use it to emit the AG-UI awaiting-tool-result event to the front.
new_messages carries the AG-UI messages generated by Agno during
the paused run (user echoes, the assistant message with tool_calls,
and any tool results emitted before the pause). It's provided because
Agno does not emit stream events from which the front can reconstruct
the assistant-with-tool-calls message — in particular, when the LLM
goes straight from reasoning to a frontend tool call without emitting
any text. Consumers typically push these messages to the front via a
:class:~ag_ui.core.events.MessagesSnapshotEvent so the client has an
authoritative view of the conversation.
PausedRunRecord
¤
flowchart TD
digitalkin.community.agno.hitl.PausedRunRecord[PausedRunRecord]
click digitalkin.community.agno.hitl.PausedRunRecord href "" "digitalkin.community.agno.hitl.PausedRunRecord"
Persistent snapshot of an Agno run paused on external tool execution.
Stored in the paused_runs collection keyed by thread_id. The
payload field holds RunOutput.to_dict() verbatim so
:meth:agno.run.agent.RunOutput.from_dict can round-trip the run on
any replica when the front replies with the tool result(s).
PausedRunStore
¤
PausedRunStore(storage: StorageStrategy)
Thin wrapper around :class:StorageStrategy for the paused_runs collection.
Owns serialization of :class:~agno.run.agent.RunOutput and keying by
thread_id. Instances are cheap — create one per trigger handler.
Parameters:
-
(storage¤StorageStrategy) –The module's storage strategy. The collection
paused_runsmust be registered with :class:PausedRunRecord— use :data:HITL_STORAGE_CONFIG.
Methods:
-
delete–Remove the paused run record for a thread.
-
load–Fetch the paused run record for a thread.
-
save–Serialize and store a paused
RunOutput.
load
async
¤
load(thread_id: str) -> PausedRunRecord | None
Fetch the paused run record for a thread.
Parameters:
Returns:
-
The(PausedRunRecord | None) –class:
PausedRunRecordif one exists, otherwiseNone.
save
async
¤
save(run_output: RunOutput, thread_id: str) -> PauseInfo
emit_awaiting_tool_result
async
¤
emit_awaiting_tool_result(
context: ModuleContext,
*,
thread_id: str,
run_id: str,
pending_tool_call_ids: list[str],
) -> None
Emit an AG-UI RunFinished with status="awaiting_tool_result".
This is the protocol signal telling the front "the run paused on a
client-side tool; execute it and reply with a ToolMessage". It
goes out via context.callbacks.send_message (bypassing the
standard :class:~digitalkin.mixins.agui_mixin.AgUiMixin event
mapping, which has no notion of an "awaiting" status).
Parameters:
-
(context¤ModuleContext) –Current module context.
-
(thread_id¤str) –AG-UI thread identifier.
-
(run_id¤str) –Run identifier to echo back in the finished event.
-
(pending_tool_call_ids¤list[str]) –The
tool_call_idvalues the front must execute and resolve — echoed inresult.pending_tool_call_idsso the front can match them.
emit_messages_snapshot
async
¤
emit_messages_snapshot(context: ModuleContext, messages: list[Message]) -> None
Emit an AG-UI MessagesSnapshot event.
Typically called just before :func:emit_awaiting_tool_result on a
paused run so the front has an authoritative view of the conversation
(including the assistant message carrying the frontend tool_calls,
which cannot be reconstructed from the streamed tool-call events alone).
Parameters:
-
(context¤ModuleContext) –Current module context.
-
(messages¤list[Message]) –List of AG-UI messages, typically produced by :func:
_agno_messages_to_aguifromRunOutput.messages.
core
¤
Core of Digitlakin defining the task management and sub-modules.
Modules:
-
common–Common utilities for the core module.
-
job_manager–Job Manager logic.
-
profiling–Profiling and monitoring tools for DigitalKin tasks and servers.
-
task_manager–Base task manager logic.
common
¤
Common utilities for the core module.
Modules:
-
factories–Common factory functions for reducing code duplication in core module.
Classes:
-
ModuleFactory–Factory for creating module instances with consistent configuration.
-
QueueFactory–Factory for creating asyncio queues with consistent configuration.
ModuleFactory
¤
Factory for creating module instances with consistent configuration.
Methods:
-
create_module_instance–Create a module instance with standard parameters.
create_module_instance
staticmethod
¤
create_module_instance(
module_class: type[BaseModule],
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> BaseModule
Create a module instance with standard parameters.
This factory method centralizes module instantiation to ensure consistent parameter passing across the codebase.
Parameters:
-
(module_class¤type[BaseModule]) –The module class to instantiate
-
(job_id¤str) –Unique job identifier
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
BaseModule–Instantiated module
Raises:
-
ValueError–If job_id or mission_id is empty
Example
module = ModuleFactory.create_module_instance( MyModule, job_id="job_123", mission_id="mission:test", setup_id="setup:config", setup_version_id="v1.0", )
QueueFactory
¤
Factory for creating asyncio queues with consistent configuration.
Methods:
-
create_bounded_queue–Create a bounded asyncio queue with standard configuration.
create_bounded_queue
staticmethod
¤
Create a bounded asyncio queue with standard configuration.
Parameters:
-
(maxsize¤int, default:DEFAULT_MAX_QUEUE_SIZE) –Maximum queue size (default 1000, 0 means unlimited)
Returns:
-
Queue–Bounded asyncio.Queue instance
Raises:
-
ValueError–If maxsize is negative
factories
¤
Common factory functions for reducing code duplication in core module.
Classes:
-
ModuleFactory–Factory for creating module instances with consistent configuration.
-
QueueFactory–Factory for creating asyncio queues with consistent configuration.
ModuleFactory
¤
Factory for creating module instances with consistent configuration.
Methods:
-
create_module_instance–Create a module instance with standard parameters.
create_module_instance
staticmethod
¤
create_module_instance(
module_class: type[BaseModule],
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> BaseModule
Create a module instance with standard parameters.
This factory method centralizes module instantiation to ensure consistent parameter passing across the codebase.
Parameters:
-
(module_class¤type[BaseModule]) –The module class to instantiate
-
(job_id¤str) –Unique job identifier
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
BaseModule–Instantiated module
Raises:
-
ValueError–If job_id or mission_id is empty
Example
module = ModuleFactory.create_module_instance( MyModule, job_id="job_123", mission_id="mission:test", setup_id="setup:config", setup_version_id="v1.0", )
QueueFactory
¤
Factory for creating asyncio queues with consistent configuration.
Methods:
-
create_bounded_queue–Create a bounded asyncio queue with standard configuration.
create_bounded_queue
staticmethod
¤
Create a bounded asyncio queue with standard configuration.
Parameters:
-
(maxsize¤int, default:DEFAULT_MAX_QUEUE_SIZE) –Maximum queue size (default 1000, 0 means unlimited)
Returns:
-
Queue–Bounded asyncio.Queue instance
Raises:
-
ValueError–If maxsize is negative
job_manager
¤
Job Manager logic.
Modules:
-
base_job_manager–Background module manager.
-
single_job_manager–Background module manager with single instance.
-
taskiq_broker–Taskiq broker & RSTREAM producer for the job manager.
-
taskiq_job_manager–Taskiq job manager module.
base_job_manager
¤
Background module manager.
Classes:
-
BaseJobManager–Abstract base class for managing background module jobs.
BaseJobManager
¤
BaseJobManager(
module_class: type[BaseModule],
services_mode: ServicesMode,
task_manager: BaseTaskManager,
)
flowchart TD
digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]
click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
Abstract base class for managing background module jobs.
Uses composition to delegate task lifecycle management to a TaskManager.
Parameters:
-
(module_class¤type[BaseModule]) –The class of the module to be managed.
-
(services_mode¤ServicesMode) –The mode of operation for the services (e.g., ASYNC or SYNC).
-
(task_manager¤BaseTaskManager) –The task manager instance to use for task lifecycle management.
Methods:
-
cancel_task–Cancel a task.
-
clean_session–Clean a task's session.
-
create_config_setup_instance_job–Create and start a new module job.
-
create_module_instance_job–Create and start a new job for the module's instance.
-
create_task–Create a task using the task manager.
-
generate_config_setup_module_response–Generate a stream consumer for a module's output data.
-
generate_stream_consumer–Generate a stream consumer for the job's message stream.
-
job_specific_callback–Generate a job-specific callback function.
-
list_modules–List all modules along with their statuses.
-
send_signal–Send signal to a task.
-
shutdown–Shutdown all tasks.
-
start–Start the job manager.
-
stop–Stop the job manager and clean up resources.
-
stop_all_modules–Stop all currently running module jobs.
-
stop_module–Stop a running module job.
-
wait_for_completion–Wait for a task to complete.
Attributes:
-
tasks(dict[str, Any]) –Get tasks from the task manager.
-
tasks_sessions(dict[str, TaskSession]) –Get task sessions from the task manager.
tasks_sessions
property
¤
tasks_sessions: dict[str, TaskSession]
Get task sessions from the task manager.
cancel_task
async
¤
Cancel a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(timeout¤float | None, default:None) –Optional timeout in seconds to wait for the cancellation to complete.
Returns:
-
bool(bool) –True if the task was successfully cancelled, False otherwise.
create_config_setup_instance_job
abstractmethod
async
¤
create_config_setup_instance_job(
config_setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Create and start a new module job.
This method initializes a new module job, assigns it a unique job ID, and starts it in the background.
Parameters:
-
(config_setup_data¤SetupModelT) –The input data required to start the job.
-
(mission_id¤str) –The mission ID associated with the job.
-
(setup_id¤str) –The setup ID.
-
(setup_version_id¤str) –The setup version ID.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
str(str) –The unique identifier (job ID) of the created job.
Raises:
-
Exception–If the module fails to start.
create_module_instance_job
abstractmethod
async
¤
create_module_instance_job(
input_data: InputModelT,
setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Create and start a new job for the module's instance.
Parameters:
-
(input_data¤InputModelT) –The input data required to start the job.
-
(setup_data¤SetupModelT) –The setup configuration for the module.
-
(mission_id¤str) –The mission ID associated with the job.
-
(setup_id¤str) –The setup ID.
-
(setup_version_id¤str) –The setup version ID associated with the module.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
str(str) –The unique identifier (job ID) of the created job.
create_task
async
¤
create_task(
task_id: str,
mission_id: str,
module: BaseModule,
coro: Coroutine[Any, Any, None],
**kwargs: Any,
) -> None
Create a task using the task manager.
Parameters:
generate_config_setup_module_response
abstractmethod
async
¤
generate_config_setup_module_response(job_id: str) -> SetupModelT | ModuleCodeModel
Generate a stream consumer for a module's output data.
This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.
Parameters:
Returns:
-
SetupModelT | ModuleCodeModel–SetupModelT | ModuleCodeModel: the SetupModelT object fully processed, or an error code.
generate_stream_consumer
abstractmethod
¤
generate_stream_consumer(
job_id: str,
) -> AbstractAsyncContextManager[AsyncGenerator[dict[str, Any], None]]
Generate a stream consumer for the job's message stream.
Parameters:
Yields:
-
AbstractAsyncContextManager[AsyncGenerator[dict[str, Any], None]]–dict[str, Any]: The messages from the associated module's stream.
job_specific_callback
async
staticmethod
¤
job_specific_callback(
callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]
list_modules
abstractmethod
async
¤
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
Send signal to a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(signal_type¤str) –Type of signal to send.
-
(payload¤dict) –Payload data for the signal.
Returns:
-
bool(bool) –True if the signal was successfully sent, False otherwise.
start
abstractmethod
async
¤
start() -> None
Start the job manager.
This method initializes any necessary resources or configurations required for the job manager to function.
stop
async
¤
stop() -> None
Stop the job manager and clean up resources.
Default no-op. Subclasses with external connections override.
stop_all_modules
abstractmethod
async
¤
stop_all_modules() -> None
Stop all currently running module jobs.
This method ensures that all active jobs are gracefully terminated.
stop_module
abstractmethod
async
¤
wait_for_completion
abstractmethod
async
¤
Wait for a task to complete.
This method blocks until the specified job has reached a terminal state. The implementation varies by job manager type: - SingleJobManager: Awaits the asyncio.Task directly - TaskiqJobManager: Polls task status
Parameters:
Raises:
-
KeyError–If the job_id is not found.
single_job_manager
¤
Background module manager with single instance.
Classes:
-
SingleJobManager–Manages a single instance of a module job.
SingleJobManager
¤
SingleJobManager(
module_class: type[BaseModule],
services_mode: ServicesMode,
default_timeout: float = 300.0,
max_concurrent_tasks: int = int(get("DIGITALKIN_MAX_CONCURRENT_TASKS", "100")),
)
flowchart TD
digitalkin.core.job_manager.single_job_manager.SingleJobManager[SingleJobManager]
digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]
digitalkin.core.job_manager.base_job_manager.BaseJobManager --> digitalkin.core.job_manager.single_job_manager.SingleJobManager
click digitalkin.core.job_manager.single_job_manager.SingleJobManager href "" "digitalkin.core.job_manager.single_job_manager.SingleJobManager"
click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
Manages a single instance of a module job.
This class ensures that only one instance of a module job is active at a time. It provides functionality to create, stop, and monitor module jobs, as well as to handle their output data.
Parameters:
-
(module_class¤type[BaseModule]) –The class of the module to be managed.
-
(services_mode¤ServicesMode) –The mode of operation for the services (e.g., ASYNC or SYNC).
-
(default_timeout¤float, default:300.0) –Default timeout for task operations
-
(max_concurrent_tasks¤int, default:int(get('DIGITALKIN_MAX_CONCURRENT_TASKS', '100'))) –Maximum number of concurrent tasks
Methods:
-
add_to_queue–Add output data to the queue for a specific job.
-
cancel_task–Cancel a task.
-
clean_session–Clean a task's session.
-
create_config_setup_instance_job–Create and start a new module setup configuration job.
-
create_module_instance_job–Create and start a new module job.
-
create_task–Create a task using the task manager.
-
generate_config_setup_module_response–Generate a stream consumer for a module's output data.
-
generate_stream_consumer–Generate a stream consumer for a module's output data.
-
job_specific_callback–Generate a job-specific callback function.
-
list_modules–List all modules along with their statuses.
-
send_signal–Send signal to a task.
-
shutdown–Shutdown all tasks.
-
start–Start manager (no-op, no external connections needed).
-
stop–Stop the job manager and clean up resources.
-
stop_all_modules–Stop all currently running module jobs.
-
stop_module–Stop a running module job.
-
wait_for_completion–Wait for a task to complete by awaiting its asyncio.Task.
Attributes:
-
tasks(dict[str, Any]) –Get tasks from the task manager.
-
tasks_sessions(dict[str, TaskSession]) –Get task sessions from the task manager.
tasks_sessions
property
¤
tasks_sessions: dict[str, TaskSession]
Get task sessions from the task manager.
add_to_queue
async
¤
add_to_queue(job_id: str, output_data: DataModel | ModuleCodeModel) -> None
Add output data to the queue for a specific job.
Behavior depends on the configured backpressure strategy: - BLOCK: await with timeout, raise TimeoutError if queue stays full. - DROP_OLDEST: wait briefly, then drop oldest message to make room. - REJECT: attempt non-blocking put, discard new message if full.
Rejects writes after stream is closed to prevent message loss.
Parameters:
-
(job_id¤str) –The unique identifier of the job.
-
(output_data¤DataModel | ModuleCodeModel) –The output data produced by the job.
Raises:
-
TimeoutError–When using BLOCK strategy and the queue remains full past the timeout.
cancel_task
async
¤
Cancel a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(timeout¤float | None, default:None) –Optional timeout in seconds to wait for the cancellation to complete.
Returns:
-
bool(bool) –True if the task was successfully cancelled, False otherwise.
create_config_setup_instance_job
async
¤
create_config_setup_instance_job(
config_setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Create and start a new module setup configuration job.
Parameters:
-
(config_setup_data¤SetupModelT) –The input data required to start the job.
-
(mission_id¤str) –The mission ID associated with the job.
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup ID.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
str(str) –The unique identifier (job ID) of the created job.
Raises:
-
Exception–If the module fails to start.
create_module_instance_job
async
¤
create_module_instance_job(
input_data: InputModelT,
setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Create and start a new module job.
Parameters:
-
(input_data¤InputModelT) –The input data required to start the job.
-
(setup_data¤SetupModelT) –The setup configuration for the module.
-
(mission_id¤str) –The mission ID associated with the job.
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup Version ID associated with the module.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
str(str) –The unique identifier (job ID) of the created job.
Raises:
-
Exception–If the module fails to start.
create_task
async
¤
create_task(
task_id: str,
mission_id: str,
module: BaseModule,
coro: Coroutine[Any, Any, None],
**kwargs: Any,
) -> None
Create a task using the task manager.
Parameters:
generate_config_setup_module_response
async
¤
generate_config_setup_module_response(job_id: str) -> SetupModelT | ModuleCodeModel
Generate a stream consumer for a module's output data.
This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.
Parameters:
Returns:
-
SetupModelT | ModuleCodeModel–SetupModelT | ModuleCodeModel: the SetupModelT object fully processed.
generate_stream_consumer
async
¤
generate_stream_consumer(
job_id: str,
) -> AsyncIterator[AsyncGenerator[dict[str, Any], None]]
Generate a stream consumer for a module's output data.
This method creates an asynchronous generator that streams output data from a specific module job. If the module does not exist, it generates an error message.
Parameters:
Yields:
-
AsyncGenerator(AsyncIterator[AsyncGenerator[dict[str, Any], None]]) –A stream of output data or error messages.
job_specific_callback
async
staticmethod
¤
job_specific_callback(
callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]
list_modules
async
¤
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
Send signal to a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(signal_type¤str) –Type of signal to send.
-
(payload¤dict) –Payload data for the signal.
Returns:
-
bool(bool) –True if the signal was successfully sent, False otherwise.
stop
async
¤
stop() -> None
Stop the job manager and clean up resources.
Default no-op. Subclasses with external connections override.
stop_module
async
¤
wait_for_completion
async
¤
taskiq_broker
¤
Taskiq broker & RSTREAM producer for the job manager.
Classes:
-
PickleFormatter–Formatter that pickles the JSON-dumped TaskiqMessage.
-
TaskiqBrokerConfig–Configuration and lifecycle management for Taskiq broker and RStream producer.
-
TaskiqLifecycleMiddleware–Lifecycle middleware for structured logging and safety-net EndOfStreamOutput.
Functions:
-
run_config_module–TaskIQ task allowing a module to compute in the background asynchronously.
-
run_start_module–TaskIQ task allowing a module to compute in the background asynchronously.
PickleFormatter
¤
flowchart TD
digitalkin.core.job_manager.taskiq_broker.PickleFormatter[PickleFormatter]
click digitalkin.core.job_manager.taskiq_broker.PickleFormatter href "" "digitalkin.core.job_manager.taskiq_broker.PickleFormatter"
Formatter that pickles the JSON-dumped TaskiqMessage.
This lets you send arbitrary Python objects (classes, functions, etc.) by first converting to JSON-safe primitives, then pickling that string.
Methods:
-
dumps–Dumps message from python complex object to JSON.
-
loads–Recreate Python object from bytes.
dumps
¤
dumps(message: TaskiqMessage) -> BrokerMessage
Dumps message from python complex object to JSON.
Parameters:
-
(message¤TaskiqMessage) –TaskIQ message
Returns:
-
BrokerMessage–BrokerMessage with mandatory information for TaskIQ
loads
¤
Recreate Python object from bytes.
Non-pickle messages (e.g. raw JSON left in the queue by other producers)
are logged and converted to a no-op TaskiqMessage so that Taskiq
acknowledges (consumes) them instead of nack-ing and re-delivering in a loop.
Parameters:
Returns:
-
TaskiqMessage–message with TaskIQ format
TaskiqBrokerConfig
¤
Configuration and lifecycle management for Taskiq broker and RStream producer.
Methods:
-
cleanup_global_resources–Clean up global resources (producer and broker connections).
-
define_broker–Create AioPikaBroker with tuned QoS for worker prefetch control.
-
define_producer–Create RStream producer with tuned settings for sustained throughput.
-
init_rstream–Init a stream for every tasks.
-
send_message_to_stream–Add a message frame to the RStream.
cleanup_global_resources
async
staticmethod
¤
cleanup_global_resources() -> None
Clean up global resources (producer and broker connections).
This should be called during shutdown to prevent connection leaks.
define_broker
staticmethod
¤
define_broker() -> AioPikaBroker
Create AioPikaBroker with tuned QoS for worker prefetch control.
Returns:
-
AioPikaBroker–Broker connected to RabbitMQ with custom formatter.
define_producer
staticmethod
¤
define_producer() -> Producer
Create RStream producer with tuned settings for sustained throughput.
Tuning:
- default_batch_publishing_delay: Flush batches every 100ms (default 3s)
for lower streaming latency during long-running tasks.
- default_context_switch_value: Yield to the event loop every 100 messages
(default 1000) to keep concurrent coroutines responsive under heavy output.
Returns:
-
Producer–Producer connected to RabbitMQ.
send_message_to_stream
async
staticmethod
¤
send_message_to_stream(job_id: str, output_data: DataModel | ModuleCodeModel) -> None
Add a message frame to the RStream.
Uses Pydantic's Rust-based model_dump_json() and direct string embedding to avoid the overhead of model_dump() → dict → json.dumps() → encode().
Parameters:
-
(job_id¤str) –ID of the job that sent the message.
-
(output_data¤DataModel | ModuleCodeModel) –Message body as a OutputModelT or error / stream_code.
TaskiqLifecycleMiddleware
¤
flowchart TD
digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware[TaskiqLifecycleMiddleware]
click digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware href "" "digitalkin.core.job_manager.taskiq_broker.TaskiqLifecycleMiddleware"
Lifecycle middleware for structured logging and safety-net EndOfStreamOutput.
Methods:
-
on_error–Safety net: send EndOfStreamOutput if worker task failed to.
-
post_execute–Log task completion.
-
pre_execute–Log task start.
on_error
async
¤
on_error(
message: TaskiqMessage, result: TaskiqResult, exception: BaseException
) -> None
Safety net: send EndOfStreamOutput if worker task failed to.
post_execute
async
¤
post_execute(message: TaskiqMessage, result: TaskiqResult) -> None
Log task completion.
pre_execute
async
¤
pre_execute(message: TaskiqMessage) -> TaskiqMessage
Log task start.
Returns:
-
TaskiqMessage–The unmodified message.
run_config_module
async
¤
run_config_module(
mission_id: str,
setup_id: str,
setup_version_id: str,
module_class: type[BaseModule],
services_mode: ServicesMode,
config_setup_data: dict,
request_metadata: dict[str, str] | None = None,
registry_config: dict[str, Any] | None = None,
context: Context = TaskiqDepends(),
) -> None
TaskIQ task allowing a module to compute in the background asynchronously.
Parameters:
-
(mission_id¤str) –str,
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup ID associated with the module.
-
(module_class¤type[BaseModule]) –type[BaseModule],
-
(services_mode¤ServicesMode) –ServicesMode,
-
(config_setup_data¤dict) –dict,
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
-
(registry_config¤dict[str, Any] | None, default:None) –Registry config (client_config) forwarded from the main process.
-
(context¤Context, default:TaskiqDepends()) –Allow TaskIQ context access
run_start_module
async
¤
run_start_module(
mission_id: str,
setup_id: str,
setup_version_id: str,
module_class: type[BaseModule],
services_mode: ServicesMode,
input_data: dict,
setup_data: dict,
request_metadata: dict[str, str] | None = None,
registry_config: dict[str, Any] | None = None,
context: Context = TaskiqDepends(),
) -> None
TaskIQ task allowing a module to compute in the background asynchronously.
Parameters:
-
(mission_id¤str) –str,
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup ID associated with the module.
-
(module_class¤type[BaseModule]) –type[BaseModule],
-
(services_mode¤ServicesMode) –ServicesMode,
-
(input_data¤dict) –dict,
-
(setup_data¤dict) –dict,
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
-
(registry_config¤dict[str, Any] | None, default:None) –Registry config (client_config) forwarded from the main process.
-
(context¤Context, default:TaskiqDepends()) –Allow TaskIQ context access
taskiq_job_manager
¤
Taskiq job manager module.
Classes:
-
TaskiqJobManager–Taskiq job manager for running modules in Taskiq tasks.
TaskiqJobManager
¤
TaskiqJobManager(
module_class: type[BaseModule],
services_mode: ServicesMode,
default_timeout: float = 300.0,
stream_timeout: float = float(get("DIGITALKIN_RSTREAM_TIMEOUT", "30.0")),
)
flowchart TD
digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager[TaskiqJobManager]
digitalkin.core.job_manager.base_job_manager.BaseJobManager[BaseJobManager]
digitalkin.core.job_manager.base_job_manager.BaseJobManager --> digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager
click digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager href "" "digitalkin.core.job_manager.taskiq_job_manager.TaskiqJobManager"
click digitalkin.core.job_manager.base_job_manager.BaseJobManager href "" "digitalkin.core.job_manager.base_job_manager.BaseJobManager"
Taskiq job manager for running modules in Taskiq tasks.
Parameters:
-
(module_class¤type[BaseModule]) –The class of the module to be managed
-
(services_mode¤ServicesMode) –The mode of operation for the services
-
(default_timeout¤float, default:300.0) –Default timeout for task operations
-
(stream_timeout¤float, default:float(get('DIGITALKIN_RSTREAM_TIMEOUT', '30.0'))) –Timeout for stream consumer operations
Methods:
-
cancel_task–Cancel a task.
-
clean_session–Clean a task's session.
-
create_config_setup_instance_job–Create and start a new module setup configuration job.
-
create_module_instance_job–Launches the module_task in Taskiq, returns the Taskiq task id as job_id.
-
create_task–Create a task using the task manager.
-
generate_config_setup_module_response–Generate a stream consumer for a module's output data.
-
generate_stream_consumer–Generate a stream consumer for the RStream stream.
-
get_module_status–Get module status from local session.
-
job_specific_callback–Generate a job-specific callback function.
-
list_modules–List all modules tracked in the registry with their statuses.
-
send_signal–Send signal to a task.
-
shutdown–Shutdown all tasks.
-
start–Start the TaskiqJobManager (no-op for external connections).
-
stop–Stop the TaskiqJobManager, cancel workers, and clean up all resources.
-
stop_all_modules–Stop all running modules tracked in the registry.
-
stop_module–Stop a running module using TaskManager.
-
wait_for_completion–Wait for a task to complete via stream-closed event.
Attributes:
-
tasks(dict[str, Any]) –Get tasks from the task manager.
-
tasks_sessions(dict[str, TaskSession]) –Get task sessions from the task manager.
tasks_sessions
property
¤
tasks_sessions: dict[str, TaskSession]
Get task sessions from the task manager.
cancel_task
async
¤
Cancel a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(timeout¤float | None, default:None) –Optional timeout in seconds to wait for the cancellation to complete.
Returns:
-
bool(bool) –True if the task was successfully cancelled, False otherwise.
create_config_setup_instance_job
async
¤
create_config_setup_instance_job(
config_setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Create and start a new module setup configuration job.
Parameters:
-
(config_setup_data¤SetupModelT) –The input data required to start the job.
-
(mission_id¤str) –The mission ID associated with the job.
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup ID.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
str(str) –The unique identifier (job ID) of the created job.
Raises:
-
TypeError–If the function is called with bad data type.
-
ValueError–If the module fails to start.
create_module_instance_job
async
¤
create_module_instance_job(
input_data: InputModelT,
setup_data: SetupModelT,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
) -> str
Launches the module_task in Taskiq, returns the Taskiq task id as job_id.
Parameters:
-
(input_data¤InputModelT) –Input data for the module
-
(setup_data¤SetupModelT) –Setup data for the module
-
(mission_id¤str) –Mission ID for the module
-
(setup_id¤str) –The setup ID associated with the module.
-
(setup_version_id¤str) –The setup ID associated with the module.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) to forward to the module.
Returns:
-
job_id(str) –The Taskiq task id.
Raises:
-
ValueError–If the task is not found.
create_task
async
¤
create_task(
task_id: str,
mission_id: str,
module: BaseModule,
coro: Coroutine[Any, Any, None],
**kwargs: Any,
) -> None
Create a task using the task manager.
Parameters:
generate_config_setup_module_response
async
¤
Generate a stream consumer for a module's output data.
Parameters:
Returns:
-
SetupModelT(SetupModelT) –the SetupModelT object fully processed.
Raises:
-
TimeoutError–If waiting for the setup response times out.
generate_stream_consumer
async
¤
generate_stream_consumer(
job_id: str,
) -> AsyncIterator[AsyncGenerator[dict[str, Any], None]]
Generate a stream consumer for the RStream stream.
Parameters:
Yields:
-
messages(AsyncIterator[AsyncGenerator[dict[str, Any], None]]) –The stream messages from the associated module.
get_module_status
async
¤
job_specific_callback
async
staticmethod
¤
job_specific_callback(
callback: Callable[[str, DataModel | ModuleCodeModel], Coroutine[Any, Any, None]],
job_id: str,
) -> Callable[[DataModel | ModuleCodeModel], Coroutine[Any, Any, None]]
list_modules
async
¤
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
Send signal to a task.
Parameters:
-
(task_id¤str) –Unique identifier for the task.
-
(mission_id¤str) –Mission identifier.
-
(signal_type¤str) –Type of signal to send.
-
(payload¤dict) –Payload data for the signal.
Returns:
-
bool(bool) –True if the signal was successfully sent, False otherwise.
stop_all_modules
async
¤
stop_all_modules() -> None
Stop all running modules tracked in the registry.
stop_module
async
¤
wait_for_completion
async
¤
Wait for a task to complete via stream-closed event.
Relies on _on_message setting _stream_closed when
end_of_stream arrives from RStream. Falls back to max_wait
timeout for crash scenarios.
Parameters:
-
(job_id¤str) –The unique identifier of the job to wait for.
-
(max_wait¤float, default:600.0) –Maximum time in seconds to wait before giving up.
Raises:
-
TimeoutError–If max_wait is exceeded.
profiling
¤
Profiling and monitoring tools for DigitalKin tasks and servers.
Modules:
-
asyncio_monitor–Server-level asyncio task monitor via asyncio-inspector.
-
task_profiler–Per-task profiling wrapper for VizTracer, Yappi, and Pyinstrument.
Classes:
-
AsyncioMonitor–Server-level asyncio task monitor with HTTP stats endpoint.
-
ProfilerMode–Profiler backend selection.
-
TaskProfiler–Per-task profiling wrapper. Zero-cost when mode is NONE.
AsyncioMonitor
¤
Server-level asyncio task monitor with HTTP stats endpoint.
Wraps asyncio-inspector to expose real-time asyncio task statistics on an HTTP endpoint. Gracefully degrades if the package is not installed.
Parameters:
Methods:
ProfilerMode
¤
flowchart TD
digitalkin.core.profiling.ProfilerMode[ProfilerMode]
click digitalkin.core.profiling.ProfilerMode href "" "digitalkin.core.profiling.ProfilerMode"
Profiler backend selection.
TaskProfiler
¤
TaskProfiler(task_id: str, mode: ProfilerMode, output_dir: str)
Per-task profiling wrapper. Zero-cost when mode is NONE.
Wraps VizTracer, Yappi, or Pyinstrument around a task's lifecycle. All exceptions are caught internally — profiler failure never crashes a task.
Yappi profiles the entire process, not individual tasks. When multiple tasks run concurrently, yappi stats reflect all of them.
Parameters:
-
(task_id¤str) –Unique identifier for the task being profiled.
-
(mode¤ProfilerMode) –Which profiler backend to use.
-
(output_dir¤str) –Directory to write profiling output files.
Methods:
asyncio_monitor
¤
Server-level asyncio task monitor via asyncio-inspector.
Classes:
-
AsyncioMonitor–Server-level asyncio task monitor with HTTP stats endpoint.
AsyncioMonitor
¤
Server-level asyncio task monitor with HTTP stats endpoint.
Wraps asyncio-inspector to expose real-time asyncio task statistics on an HTTP endpoint. Gracefully degrades if the package is not installed.
Parameters:
Methods:
task_profiler
¤
Per-task profiling wrapper for VizTracer, Yappi, and Pyinstrument.
Classes:
-
ProfilerMode–Profiler backend selection.
-
TaskProfiler–Per-task profiling wrapper. Zero-cost when mode is NONE.
ProfilerMode
¤
flowchart TD
digitalkin.core.profiling.task_profiler.ProfilerMode[ProfilerMode]
click digitalkin.core.profiling.task_profiler.ProfilerMode href "" "digitalkin.core.profiling.task_profiler.ProfilerMode"
Profiler backend selection.
TaskProfiler
¤
TaskProfiler(task_id: str, mode: ProfilerMode, output_dir: str)
Per-task profiling wrapper. Zero-cost when mode is NONE.
Wraps VizTracer, Yappi, or Pyinstrument around a task's lifecycle. All exceptions are caught internally — profiler failure never crashes a task.
Yappi profiles the entire process, not individual tasks. When multiple tasks run concurrently, yappi stats reflect all of them.
Parameters:
-
(task_id¤str) –Unique identifier for the task being profiled.
-
(mode¤ProfilerMode) –Which profiler backend to use.
-
(output_dir¤str) –Directory to write profiling output files.
Methods:
task_manager
¤
Base task manager logic.
Modules:
-
base_task_manager–Base task manager with common lifecycle management.
-
local_task_manager–Local task manager for single-process execution.
-
remote_task_manager–Remote task manager for distributed execution.
-
task_executor–Task executor for running tasks with full lifecycle management.
-
task_session–Task session easing task lifecycle management.
base_task_manager
¤
Base task manager with common lifecycle management.
Classes:
-
BaseTaskManager–Base task manager with common lifecycle management.
BaseTaskManager
¤
BaseTaskManager(default_timeout: float = 300.0)
flowchart TD
digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]
click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
Base task manager with common lifecycle management.
Provides shared functionality for task orchestration, monitoring, signaling, and cancellation. Subclasses implement specific execution strategies (local or remote).
Parameters:
Methods:
-
__aenter__–Enter async context manager.
-
__aexit__–Exit async context manager and clean up resources.
-
cancel_all_tasks–Cancel all running tasks.
-
cancel_task–Cancel a task with graceful shutdown and fallback.
-
clean_session–Force cleanup of task session, cancelling the task if still running.
-
create_task–Create and manage a new task.
-
send_signal–Send signal to a specific task.
-
shutdown–Graceful shutdown of all tasks.
Attributes:
-
max_concurrent_tasks(int) –Maximum number of concurrent tasks.
-
running_tasks(set[str]) –Get IDs of currently running tasks.
-
task_count(int) –Number of active tasks (pending or running).
max_concurrent_tasks
property
writable
¤
max_concurrent_tasks: int
Maximum number of concurrent tasks.
__aenter__
async
¤
__aenter__() -> Self
Enter async context manager.
Returns:
-
Self–Self for use in async with statements
__aexit__
async
¤
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit async context manager and clean up resources.
Parameters:
-
(exc_type¤type[BaseException] | None) –Exception type if an exception occurred
-
(exc_val¤BaseException | None) –Exception value if an exception occurred
-
(exc_tb¤TracebackType | None) –Exception traceback if an exception occurred
cancel_all_tasks
async
¤
cancel_all_tasks(
mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]
cancel_task
async
¤
Cancel a task with graceful shutdown and fallback.
Parameters:
-
(task_id¤str) –The ID of the task to cancel
-
(mission_id¤str) –The ID of the mission
-
(timeout¤float | None, default:None) –Optional timeout for cancellation
Returns:
-
bool–True if the task was cancelled successfully, False otherwise
create_task
abstractmethod
async
¤
create_task(
task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None
Create and manage a new task.
Subclasses implement specific execution strategies.
Parameters:
-
(task_id¤str) –Unique identifier for the task
-
(mission_id¤str) –Mission identifier
-
(module¤BaseModule) –Module instance to execute
-
(coro¤Coroutine[Any, Any, None]) –Coroutine to execute
Raises:
-
ValueError–If task_id duplicated
-
RuntimeError–If task overload
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
local_task_manager
¤
Local task manager for single-process execution.
Classes:
-
LocalTaskManager–Task manager for local execution in the same process.
LocalTaskManager
¤
LocalTaskManager(default_timeout: float = 10.0)
flowchart TD
digitalkin.core.task_manager.local_task_manager.LocalTaskManager[LocalTaskManager]
digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]
digitalkin.core.task_manager.base_task_manager.BaseTaskManager --> digitalkin.core.task_manager.local_task_manager.LocalTaskManager
click digitalkin.core.task_manager.local_task_manager.LocalTaskManager href "" "digitalkin.core.task_manager.local_task_manager.LocalTaskManager"
click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
Task manager for local execution in the same process.
Executes tasks locally using TaskExecutor with the supervisor pattern. Suitable for single-server deployments and development.
Parameters:
Methods:
-
__aenter__–Enter async context manager.
-
__aexit__–Exit async context manager and clean up resources.
-
cancel_all_tasks–Cancel all running tasks.
-
cancel_task–Cancel a task with graceful shutdown and fallback.
-
clean_session–Force cleanup of task session, cancelling the task if still running.
-
create_task–Create and execute a task locally using TaskExecutor.
-
send_signal–Send signal to a specific task.
-
shutdown–Graceful shutdown of all tasks.
Attributes:
-
max_concurrent_tasks(int) –Maximum number of concurrent tasks.
-
running_tasks(set[str]) –Get IDs of currently running tasks.
-
task_count(int) –Number of active tasks (pending or running).
max_concurrent_tasks
property
writable
¤
max_concurrent_tasks: int
Maximum number of concurrent tasks.
__aenter__
async
¤
__aenter__() -> Self
Enter async context manager.
Returns:
-
Self–Self for use in async with statements
__aexit__
async
¤
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit async context manager and clean up resources.
Parameters:
-
(exc_type¤type[BaseException] | None) –Exception type if an exception occurred
-
(exc_val¤BaseException | None) –Exception value if an exception occurred
-
(exc_tb¤TracebackType | None) –Exception traceback if an exception occurred
cancel_all_tasks
async
¤
cancel_all_tasks(
mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]
cancel_task
async
¤
Cancel a task with graceful shutdown and fallback.
Parameters:
-
(task_id¤str) –The ID of the task to cancel
-
(mission_id¤str) –The ID of the mission
-
(timeout¤float | None, default:None) –Optional timeout for cancellation
Returns:
-
bool–True if the task was cancelled successfully, False otherwise
create_task
async
¤
create_task(
task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None
Create and execute a task locally using TaskExecutor.
Parameters:
-
(task_id¤str) –Unique identifier for the task
-
(mission_id¤str) –Mission identifier
-
(module¤BaseModule) –Module instance to execute
-
(coro¤Coroutine[Any, Any, None]) –Coroutine to execute
Raises:
-
ValueError–If task_id duplicated
-
RuntimeError–If task overload
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
remote_task_manager
¤
Remote task manager for distributed execution.
Classes:
-
RemoteTaskManager–Task manager for distributed/remote execution.
RemoteTaskManager
¤
RemoteTaskManager(default_timeout: float = 300.0)
flowchart TD
digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager[RemoteTaskManager]
digitalkin.core.task_manager.base_task_manager.BaseTaskManager[BaseTaskManager]
digitalkin.core.task_manager.base_task_manager.BaseTaskManager --> digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager
click digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager href "" "digitalkin.core.task_manager.remote_task_manager.RemoteTaskManager"
click digitalkin.core.task_manager.base_task_manager.BaseTaskManager href "" "digitalkin.core.task_manager.base_task_manager.BaseTaskManager"
Task manager for distributed/remote execution.
Only manages task metadata and signals - actual execution happens in remote workers. Suitable for horizontally scaled deployments with Taskiq/Celery workers.
Parameters:
Methods:
-
__aenter__–Enter async context manager.
-
__aexit__–Exit async context manager and clean up resources.
-
cancel_all_tasks–Cancel all running tasks.
-
cancel_task–Cancel a task with graceful shutdown and fallback.
-
clean_session–Force cleanup of task session, cancelling the task if still running.
-
create_task–Register task for remote execution (metadata only).
-
send_signal–Send signal to a specific task.
-
shutdown–Graceful shutdown of all tasks.
Attributes:
-
max_concurrent_tasks(int) –Maximum number of concurrent tasks.
-
running_tasks(set[str]) –Get IDs of currently running tasks.
-
task_count(int) –Number of active tasks (pending or running).
max_concurrent_tasks
property
writable
¤
max_concurrent_tasks: int
Maximum number of concurrent tasks.
__aenter__
async
¤
__aenter__() -> Self
Enter async context manager.
Returns:
-
Self–Self for use in async with statements
__aexit__
async
¤
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit async context manager and clean up resources.
Parameters:
-
(exc_type¤type[BaseException] | None) –Exception type if an exception occurred
-
(exc_val¤BaseException | None) –Exception value if an exception occurred
-
(exc_tb¤TracebackType | None) –Exception traceback if an exception occurred
cancel_all_tasks
async
¤
cancel_all_tasks(
mission_id: str, timeout: float | None = None
) -> dict[str, bool | BaseException]
cancel_task
async
¤
Cancel a task with graceful shutdown and fallback.
Parameters:
-
(task_id¤str) –The ID of the task to cancel
-
(mission_id¤str) –The ID of the mission
-
(timeout¤float | None, default:None) –Optional timeout for cancellation
Returns:
-
bool–True if the task was cancelled successfully, False otherwise
create_task
async
¤
create_task(
task_id: str, mission_id: str, module: BaseModule, coro: Coroutine[Any, Any, None]
) -> None
Register task for remote execution (metadata only).
Creates TaskSession for signal handling and monitoring, but doesn't execute the coroutine. The coroutine will be recreated and executed by a remote worker.
Parameters:
-
(task_id¤str) –Unique identifier for the task
-
(mission_id¤str) –Mission identifier
-
(module¤BaseModule) –Module instance for metadata (not executed here)
-
(coro¤Coroutine[Any, Any, None]) –Coroutine (will be closed - execution happens in worker)
Raises:
-
ValueError–If task_id duplicated
-
RuntimeError–If task overload
send_signal
async
¤
send_signal(task_id: str, mission_id: str, signal_type: str, payload: dict) -> bool
task_executor
¤
Task executor for running tasks with full lifecycle management.
Classes:
-
TaskExecutor–Executes tasks with the supervisor pattern (main + signal listener).
TaskExecutor
¤
Executes tasks with the supervisor pattern (main + signal listener).
Pure execution logic - no task registry or orchestration. Used by workers to run distributed tasks or by TaskManager for local execution.
Methods:
-
execute_task–Execute a task using the supervisor pattern.
execute_task
async
staticmethod
¤
execute_task(
task_id: str, mission_id: str, coro: Coroutine[Any, Any, None], session: TaskSession
) -> Task[None]
Execute a task using the supervisor pattern.
Runs two concurrent sub-tasks: - Main coroutine (the actual work) - Signal listener (watches for stop/cancel signals)
The first task to complete determines the outcome.
Parameters:
-
(task_id¤str) –Unique identifier for the task
-
(mission_id¤str) –Mission identifier for the task
-
(coro¤Coroutine[Any, Any, None]) –The coroutine to execute (module.start(...))
-
(session¤TaskSession) –TaskSession for state management
Returns:
-
Task[None]–asyncio.Task: The supervisor task managing the lifecycle
task_session
¤
Task session easing task lifecycle management.
Classes:
-
TaskSession–Task Session with lifecycle management.
TaskSession
¤
TaskSession(
task_id: str, mission_id: str, module: BaseModule, queue_maxsize: int = 1000
)
Task Session with lifecycle management.
The Session defines the whole lifecycle of a task as an ephemeral context.
Parameters:
-
(task_id¤str) –Unique task identifier
-
(mission_id¤str) –Mission identifier
-
(module¤BaseModule) –Module instance
-
(queue_maxsize¤int, default:1000) –Maximum size for the queue (0 = unlimited)
Methods:
-
cleanup–Clean up task session resources.
-
close_stream–Signal that the stream should terminate.
-
listen_signals–Signal listener for cancel signals via TaskManagerStrategy.
-
record_exception–Record exception details for logging.
Attributes:
-
cancelled(bool) –Task cancellation status.
-
session_ids(dict[str, str]) –Get all session IDs from module context for structured logging.
-
setup_id(str) –Get setup_id from module context.
-
setup_version_id(str) –Get setup_version_id from module context.
-
stream_closed(bool) –Check if stream termination was signaled.
session_ids
property
¤
Get all session IDs from module context for structured logging.
cleanup
async
¤
cleanup() -> None
Clean up task session resources.
This method is idempotent - safe to call multiple times. Second and subsequent calls are no-ops.
This includes: - Clearing queue to free memory - Cleaning up module context services - Stopping module - Clearing module reference
listen_signals
async
¤
listen_signals() -> None
Signal listener for cancel signals via TaskManagerStrategy.
Subscribes to signal updates for this task_id and processes cancel signals.
Raises:
-
CancelledError–If task is cancelled during signal listening.
grpc_servers
¤
This package contains the gRPC server and client implementations.
Modules:
-
module_server–Module gRPC server implementation for DigitalKin.
-
module_servicer–Module servicer implementation for DigitalKin.
-
utils–gRPC servers utilities package.
module_server
¤
Module gRPC server implementation for DigitalKin.
Classes:
-
ModuleServer–gRPC server for a DigitalKin module.
ModuleServer
¤
ModuleServer(
module_class: type[BaseModule],
client_config: ClientConfig | None = None,
interceptors: Sequence[Any] | None = None,
)
flowchart TD
digitalkin.grpc_servers.module_server.ModuleServer[ModuleServer]
digitalkin.grpc_servers._base_server.BaseServer[BaseServer]
digitalkin.grpc_servers._base_server.BaseServer --> digitalkin.grpc_servers.module_server.ModuleServer
click digitalkin.grpc_servers.module_server.ModuleServer href "" "digitalkin.grpc_servers.module_server.ModuleServer"
click digitalkin.grpc_servers._base_server.BaseServer href "" "digitalkin.grpc_servers._base_server.BaseServer"
gRPC server for a DigitalKin module.
This server exposes the module's functionality through the ModuleService gRPC interface. It can optionally register itself with a Registry server.
Attributes:
-
module–The module instance being served.
-
server_config–Server configuration.
-
client_config–Setup client configuration.
-
module_servicer(ModuleServicer | None) –The gRPC servicer handling module requests.
Parameters:
-
(module_class¤type[BaseModule]) –The module instance to be served.
-
(client_config¤ClientConfig | None, default:None) –Client configuration used by services and registry connection.
-
(interceptors¤Sequence[Any] | None, default:None) –Optional sequence of gRPC server interceptors.
Methods:
-
await_termination–Wait for the async server to terminate.
-
register_servicer–Register a servicer with the gRPC server and track it for reflection.
-
start–Start the module server and register with the registry if configured.
-
start_async–Start the module server and register with the registry if configured.
-
stop–Stop the gRPC server and close all cached gRPC client channels.
-
stop_async–Stop the module server with async cleanup.
-
wait_for_termination–Wait for the server to terminate.
await_termination
async
¤
await_termination() -> None
Wait for the async server to terminate.
This method should only be used with async servers.
register_servicer
¤
register_servicer(
servicer: T,
add_to_server_fn: Callable[[T, GrpcServer], None],
service_descriptor: ServiceDescriptor | None = None,
service_names: list[str] | None = None,
) -> None
Register a servicer with the gRPC server and track it for reflection.
Parameters:
-
(servicer¤T) –The servicer implementation instance
-
(add_to_server_fn¤Callable[[T, GrpcServer], None]) –The function to add the servicer to the server
-
(service_descriptor¤ServiceDescriptor | None, default:None) –Optional service descriptor (pb2 DESCRIPTOR)
-
(service_names¤list[str] | None, default:None) –Optional explicit list of service full names
Raises:
-
ServicerError–If the server is not created before calling
start_async
async
¤
start_async() -> None
Start the module server and register with the registry if configured.
stop
¤
stop_async
async
¤
stop_async(grace: float | None = None) -> None
Stop the module server with async cleanup.
Deregisters from registry and stops the server. Modules also become inactive when they stop sending heartbeats as a fallback.
wait_for_termination
¤
wait_for_termination() -> None
Wait for the server to terminate.
In synchronous mode, this blocks until the server is terminated.
In asynchronous mode, a warning is logged suggesting to use await_termination.
module_servicer
¤
Module servicer implementation for DigitalKin.
Classes:
-
ModuleServicer–Implementation of the ModuleService.
ModuleServicer
¤
ModuleServicer(module_class: type[BaseModule])
flowchart TD
digitalkin.grpc_servers.module_servicer.ModuleServicer[ModuleServicer]
digitalkin.utils.arg_parser.ArgParser[ArgParser]
digitalkin.utils.arg_parser.ArgParser --> digitalkin.grpc_servers.module_servicer.ModuleServicer
click digitalkin.grpc_servers.module_servicer.ModuleServicer href "" "digitalkin.grpc_servers.module_servicer.ModuleServicer"
click digitalkin.utils.arg_parser.ArgParser href "" "digitalkin.utils.arg_parser.ArgParser"
Implementation of the ModuleService.
This servicer handles interactions with a DigitalKin module.
Attributes:
-
module–The module instance being served.
-
active_jobs–Dictionary tracking active module jobs.
Parameters:
Classes:
-
HelpAction–Custom HelpAction to display subparsers helps too.
Methods:
-
ConfigSetupModule–Configure the module setup.
-
GetConfigSetupModule–Get information about the module's setup and configuration.
-
GetModuleCost–Get information about the module's cost configuration.
-
GetModuleInput–Get information about the module's expected input.
-
GetModuleOutput–Get information about the module's expected output.
-
GetModuleSecret–Get information about the module's secrets.
-
GetModuleSelectInput–Get the trigger selection schema for the module.
-
GetModuleSetup–Get information about the module's setup and configuration.
-
StartModule–Start a module execution.
-
StopModule–Stop a running module execution.
-
shutdown–Release servicer-level resources (GrpcSetup channel, registry cache).
HelpAction
¤
flowchart TD
digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction[HelpAction]
click digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction href "" "digitalkin.grpc_servers.module_servicer.ModuleServicer.HelpAction"
Custom HelpAction to display subparsers helps too.
Methods:
-
__call__–Override the HelpActions as it doesn't handle subparser well.
ConfigSetupModule
async
¤
ConfigSetupModule(
request: ConfigSetupModuleRequest, context: ServicerContext
) -> ConfigSetupModuleResponse
Configure the module setup.
Parameters:
-
(request¤ConfigSetupModuleRequest) –The configuration request.
-
(context¤ServicerContext) –The gRPC context.
Returns:
-
ConfigSetupModuleResponse–A response indicating success or failure.
Raises:
-
ServicerError–if the setup data is not returned or job creation fails.
GetConfigSetupModule
async
¤
GetModuleCost
async
¤
GetModuleInput
async
¤
GetModuleOutput
async
¤
GetModuleSecret
async
¤
GetModuleSelectInput
async
¤
GetModuleSetup
async
¤
StartModule
async
¤
StartModule(
request: StartModuleRequest, context: ServicerContext
) -> AsyncGenerator[StartModuleResponse, Any]
Start a module execution.
Parameters:
-
(request¤StartModuleRequest) –Iterator of start module requests.
-
(context¤ServicerContext) –The gRPC context.
Yields:
-
AsyncGenerator[StartModuleResponse, Any]–Responses during module execution.
Raises:
-
ServicerError–the necessary query didn't work.
StopModule
async
¤
shutdown
async
¤
shutdown() -> None
Release servicer-level resources (GrpcSetup channel, registry cache).
utils
¤
gRPC servers utilities package.
Modules:
-
exceptions–Exceptions for the DigitalKin gRPC package.
-
grpc_client_wrapper–Client wrapper to ease channel creation with specific ServerConfig.
-
grpc_error_handler–Shared error handling utilities for gRPC services.
-
utility_schema_extender–Utility schema extender for gRPC API responses.
exceptions
¤
Exceptions for the DigitalKin gRPC package.
Classes:
-
ConfigurationError–Error related to server configuration.
-
DigitalKinError–Base exception for all DigitalKin errors.
-
ReflectionError–Error related to gRPC reflection service.
-
SecurityError–Error related to security configuration.
-
ServerError–Base class for server-related errors.
-
ServerStateError–Error related to server state (e.g., already started, not started).
-
ServicerError–Error related to servicer operations.
ConfigurationError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.ConfigurationError[ConfigurationError]
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ConfigurationError
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.ConfigurationError href "" "digitalkin.grpc_servers.utils.exceptions.ConfigurationError"
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Error related to server configuration.
DigitalKinError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Base exception for all DigitalKin errors.
ReflectionError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.ReflectionError[ReflectionError]
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ReflectionError
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.ReflectionError href "" "digitalkin.grpc_servers.utils.exceptions.ReflectionError"
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Error related to gRPC reflection service.
SecurityError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.SecurityError[SecurityError]
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.SecurityError
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.SecurityError href "" "digitalkin.grpc_servers.utils.exceptions.SecurityError"
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Error related to security configuration.
ServerError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Base class for server-related errors.
ServerStateError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.ServerStateError[ServerStateError]
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ServerStateError
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.ServerStateError href "" "digitalkin.grpc_servers.utils.exceptions.ServerStateError"
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Error related to server state (e.g., already started, not started).
ServicerError
¤
flowchart TD
digitalkin.grpc_servers.utils.exceptions.ServicerError[ServicerError]
digitalkin.grpc_servers.utils.exceptions.ServerError[ServerError]
digitalkin.grpc_servers.utils.exceptions.DigitalKinError[DigitalKinError]
digitalkin.grpc_servers.utils.exceptions.ServerError --> digitalkin.grpc_servers.utils.exceptions.ServicerError
digitalkin.grpc_servers.utils.exceptions.DigitalKinError --> digitalkin.grpc_servers.utils.exceptions.ServerError
click digitalkin.grpc_servers.utils.exceptions.ServicerError href "" "digitalkin.grpc_servers.utils.exceptions.ServicerError"
click digitalkin.grpc_servers.utils.exceptions.ServerError href "" "digitalkin.grpc_servers.utils.exceptions.ServerError"
click digitalkin.grpc_servers.utils.exceptions.DigitalKinError href "" "digitalkin.grpc_servers.utils.exceptions.DigitalKinError"
Error related to servicer operations.
grpc_client_wrapper
¤
Client wrapper to ease channel creation with specific ServerConfig.
Classes:
-
GrpcClientWrapper–gRPC client shared by the different services.
GrpcClientWrapper
¤
gRPC client shared by the different services.
Subclasses should set the service_name class attribute to identify the gRPC service in logs (e.g., "SetupService", "RegistryService").
Channels are cached at the class level and ref-counted. gRPC HTTP/2 channels natively multiplex concurrent streams on a single connection, so sharing a channel across tasks is safe and efficient.
Methods:
-
close–Release this instance's gRPC channel ref. Subclasses override to release extra resources.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close
async
¤
close() -> None
Release this instance's gRPC channel ref. Subclasses override to release extra resources.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
grpc_error_handler
¤
Shared error handling utilities for gRPC services.
Classes:
-
GrpcErrorHandlerMixin–Mixin class providing common gRPC error handling functionality.
GrpcErrorHandlerMixin
¤
Mixin class providing common gRPC error handling functionality.
Methods:
-
handle_grpc_errors–Handle gRPC errors for the given operation.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
utility_schema_extender
¤
Utility schema extender for gRPC API responses.
This module extends module schemas with SDK utility protocols for API responses.
Classes:
-
UtilitySchemaExtender–Extends module schemas with SDK utility protocols for API responses.
UtilitySchemaExtender
¤
Extends module schemas with SDK utility protocols for API responses.
This class provides methods to create extended Pydantic models that include both user-defined protocols and SDK utility protocols in their schemas.
Methods:
-
create_extended_input_model–Create an extended input model that includes utility input protocols.
-
create_extended_output_model–Create an extended output model that includes utility output protocols.
create_extended_input_model
classmethod
¤
create_extended_input_model(base_model: type[DataModel]) -> type[DataModel]
Create an extended input model that includes utility input protocols.
Parameters:
Returns:
logger
¤
This module sets up a logger.
Classes:
-
ColorJSONFormatter–Color JSON formatter for development (pretty-printed with colors).
-
PlainJSONFormatter–Plain JSON formatter for log files (no ANSI colors, compact JSON).
Functions:
-
add_file_handler–Add a rotating file handler to a logger if
DIGITALKIN_LOG_DIRis set. -
setup_logger–Set up a logger with the ColorJSONFormatter.
ColorJSONFormatter
¤
ColorJSONFormatter(*, is_production: bool = False)
flowchart TD
digitalkin.logger.ColorJSONFormatter[ColorJSONFormatter]
click digitalkin.logger.ColorJSONFormatter href "" "digitalkin.logger.ColorJSONFormatter"
Color JSON formatter for development (pretty-printed with colors).
Parameters:
Methods:
-
format–Format the log record as colored JSON for development.
PlainJSONFormatter
¤
flowchart TD
digitalkin.logger.PlainJSONFormatter[PlainJSONFormatter]
click digitalkin.logger.PlainJSONFormatter href "" "digitalkin.logger.PlainJSONFormatter"
Plain JSON formatter for log files (no ANSI colors, compact JSON).
Methods:
-
format–Format the log record as compact JSON for file output.
add_file_handler
¤
Add a rotating file handler to a logger if DIGITALKIN_LOG_DIR is set.
Only creates log files when the environment variable is explicitly set
and points to an existing directory. Attaches a :class:RotatingFileHandler
(10 MB, 5 backups) with :class:PlainJSONFormatter at DEBUG level.
Parameters:
setup_logger
¤
setup_logger(
name: str,
level: int = INFO,
additional_loggers: dict[str, int] | None = None,
*,
is_production: bool | None = None,
configure_root: bool = True,
) -> Logger
Set up a logger with the ColorJSONFormatter.
Parameters:
-
(name¤str) –Name of the logger to create
-
(level¤int, default:INFO) –Logging level (default: logging.INFO)
-
(is_production¤bool | None, default:None) –Whether running in production. If None, checks RAILWAY_SERVICE_NAME env var
-
(configure_root¤bool, default:True) –Whether to configure root logger (default: True)
-
(additional_loggers¤dict[str, int] | None, default:None) –Dict of additional logger names and their levels to configure
Returns:
-
Logger–logging.Logger: Configured logger instance
mixins
¤
Mixin definitions.
Modules:
-
agui_mixin–AG-UI event streaming mixin for DigitalKin modules.
-
base_mixin–Simple toolkit class with basic and simple API access in the Triggers.
-
callback_mixin–User callback to send a message from the Trigger.
-
chat_history_mixin–Context mixins providing ergonomic access to service strategies.
-
cost_mixin–Cost Mixin to ease trigger deveolpment.
-
file_history_mixin–Context mixins providing ergonomic access to service strategies.
-
filesystem_mixin–Filesystem Mixin to ease filesystem use.
-
logger_mixin–Logger Mixin to ease and merge every logs.
-
storage_mixin–Storage Mixin to ease storage access in Triggers.
Classes:
-
AgUiMixin–Mixin for converting agent events to AG-UI protocol and sending them.
-
BaseMixin–Base Mixin to access to minimum Module Context functionnalities in the Triggers.
-
CostMixin–Mixin providing cost tracking operations through the cost strategy.
-
FilesystemMixin–Mixin providing filesystem operations through the filesystem strategy.
-
LoggerMixin–Mixin providing callback operations through the callbacks strategy.
-
StorageMixin–Mixin providing storage operations through the storage strategy.
AgUiMixin
¤
AgUiMixin()
Mixin for converting agent events to AG-UI protocol and sending them.
This mixin is a stateless emitter: each handler reads IDs from the event and emits the corresponding AG-UI event(s). The adapter is responsible for generating IDs and managing event lifecycle (start/complete sequences).
Usage::
class MyTrigger(BaseTrigger, AgUiMixin):
async def execute(self, context, input_data):
async for event in agent.run(input_data.message, stream=True):
await self.agui_send_message(context, event)
Methods:
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
BaseMixin
¤
BaseMixin()
flowchart TD
digitalkin.mixins.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.BaseMixin
click digitalkin.mixins.BaseMixin href "" "digitalkin.mixins.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Base Mixin to access to minimum Module Context functionnalities in the Triggers.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
CostMixin
¤
Mixin providing cost tracking operations through the cost strategy.
This mixin wraps cost strategy calls to provide a cleaner API for cost tracking in trigger handlers. Cost failures are non-critical and never crash tasks.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
FilesystemMixin
¤
Mixin providing filesystem operations through the filesystem strategy.
This mixin wraps filesystem strategy calls to provide a cleaner API for file operations in trigger handlers.
Methods:
-
get_file–Retrieve a file by ID with the content.
-
upload_files–Upload files using the filesystem strategy.
get_file
async
staticmethod
¤
get_file(context: ModuleContext, file_id: str) -> FilesystemRecord
Retrieve a file by ID with the content.
Parameters:
-
(context¤ModuleContext) –Module context containing the filesystem strategy
-
(file_id¤str) –Unique identifier for the file
Returns:
-
FilesystemRecord–File object with metadata and optionally content
Raises:
-
FilesystemServiceError–If file retrieval fails
upload_files
async
staticmethod
¤
upload_files(
context: ModuleContext, files: list[Any]
) -> tuple[list[FilesystemRecord], int, int]
Upload files using the filesystem strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the filesystem strategy
-
(files¤list[Any]) –List of files to upload
Returns:
-
tuple[list[FilesystemRecord], int, int]–Tuple of (all_files, succeeded_files, failed_files)
Raises:
-
FilesystemServiceError–If upload operation fails
LoggerMixin
¤
Mixin providing callback operations through the callbacks strategy.
This mixin wraps callback strategy calls to provide a cleaner API for logging and messaging in trigger handlers.
Methods:
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
StorageMixin
¤
Mixin providing storage operations through the storage strategy.
This mixin wraps storage strategy calls to provide a cleaner API for trigger handlers.
Methods:
-
read_storage–Read data from storage.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
agui_mixin
¤
AG-UI event streaming mixin for DigitalKin modules.
This mixin provides utilities to convert framework-agnostic agent events into AG-UI protocol events and send them through the module context callbacks.
The mixin is a stateless emitter: it receives events with all necessary info (including IDs) and emits the corresponding AG-UI protocol events. All state management (ID generation, lifecycle tracking) belongs in the adapter layer.
Classes:
-
AgUiMixin–Mixin for converting agent events to AG-UI protocol and sending them.
AgUiMixin
¤
AgUiMixin()
Mixin for converting agent events to AG-UI protocol and sending them.
This mixin is a stateless emitter: each handler reads IDs from the event and emits the corresponding AG-UI event(s). The adapter is responsible for generating IDs and managing event lifecycle (start/complete sequences).
Usage::
class MyTrigger(BaseTrigger, AgUiMixin):
async def execute(self, context, input_data):
async for event in agent.run(input_data.message, stream=True):
await self.agui_send_message(context, event)
Methods:
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
base_mixin
¤
Simple toolkit class with basic and simple API access in the Triggers.
Classes:
-
BaseMixin–Base Mixin to access to minimum Module Context functionnalities in the Triggers.
BaseMixin
¤
BaseMixin()
flowchart TD
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Base Mixin to access to minimum Module Context functionnalities in the Triggers.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
callback_mixin
¤
User callback to send a message from the Trigger.
.. deprecated::
Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.
Classes:
-
UserMessageMixin–Mixin providing callback operations through the callbacks.
UserMessageMixin
¤
flowchart TD
digitalkin.mixins.callback_mixin.UserMessageMixin[UserMessageMixin]
click digitalkin.mixins.callback_mixin.UserMessageMixin href "" "digitalkin.mixins.callback_mixin.UserMessageMixin"
Mixin providing callback operations through the callbacks.
.. deprecated::
Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.
Methods:
-
__init_subclass__–Deprecated warning.
-
send_message–Send a message using the callbacks strategy.
send_message
async
staticmethod
¤
send_message(context: ModuleContext, output: OutputModelT) -> None
Send a message using the callbacks strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(output¤OutputModelT) –Message to send with the Module defined output Type.
chat_history_mixin
¤
Context mixins providing ergonomic access to service strategies.
.. deprecated::
Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.
Classes:
-
ChatHistoryMixin–Mixin providing chat history operations through storage strategy.
ChatHistoryMixin
¤
ChatHistoryMixin()
flowchart TD
digitalkin.mixins.chat_history_mixin.ChatHistoryMixin[ChatHistoryMixin]
digitalkin.mixins.callback_mixin.UserMessageMixin[UserMessageMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.callback_mixin.UserMessageMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.chat_history_mixin.ChatHistoryMixin
click digitalkin.mixins.chat_history_mixin.ChatHistoryMixin href "" "digitalkin.mixins.chat_history_mixin.ChatHistoryMixin"
click digitalkin.mixins.callback_mixin.UserMessageMixin href "" "digitalkin.mixins.callback_mixin.UserMessageMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Mixin providing chat history operations through storage strategy.
.. deprecated::
Use :class:digitalkin.mixins.agui_mixin.AgUiMixin instead.
Methods:
-
__init_subclass__–Deprecated warning.
-
append_chat_history_message–Append a message to chat history.
-
clear_ch_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_chat_history–Flush the current mission's dirty chat history to storage.
-
load_chat_history–Load chat history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
save_send_message–Save output to chat history and send response to the module request.
-
send_message–Send a message using the callbacks strategy.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
append_chat_history_message
async
¤
append_chat_history_message(context: ModuleContext, role: Role, content: Any) -> None
Append a message to chat history.
The message is added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_CHAT_HISTORY_FLUSH_THRESHOLD) or flush_chat_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(role¤Role) –Message role (user, assistant, system).
-
(content¤Any) –Message content.
clear_ch_mission_cache
¤
clear_ch_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_chat_history
async
¤
flush_chat_history(context: ModuleContext) -> None
Flush the current mission's dirty chat history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
load_chat_history
async
¤
load_chat_history(context: ModuleContext) -> ChatHistory
Load chat history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
ChatHistory–Chat history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
save_send_message
async
¤
save_send_message(context: ModuleContext, output: OutputModelT, role: Role) -> None
Save output to chat history and send response to the module request.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(role¤Role) –Message role (user, assistant, system).
-
(output¤OutputModelT) –Message content as Pydantic Class.
send_message
async
staticmethod
¤
send_message(context: ModuleContext, output: OutputModelT) -> None
Send a message using the callbacks strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(output¤OutputModelT) –Message to send with the Module defined output Type.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
cost_mixin
¤
Cost Mixin to ease trigger deveolpment.
Classes:
-
CostMixin–Mixin providing cost tracking operations through the cost strategy.
CostMixin
¤
Mixin providing cost tracking operations through the cost strategy.
This mixin wraps cost strategy calls to provide a cleaner API for cost tracking in trigger handlers. Cost failures are non-critical and never crash tasks.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
file_history_mixin
¤
Context mixins providing ergonomic access to service strategies.
This module provides mixins that wrap service strategy calls with cleaner APIs, following Django/FastAPI patterns where context is passed explicitly to each method.
Classes:
-
FileHistoryMixin–Mixin providing file history operations through storage strategy.
FileHistoryMixin
¤
FileHistoryMixin()
flowchart TD
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Mixin providing file history operations through storage strategy.
File histories are cached in memory after first load to avoid redundant gRPC reads. Known-persisted keys use update_storage (1 call) instead of upsert_storage (2 calls).
Writes are batched: files accumulate in the cache and are flushed when the batch threshold is reached or flush_file_history() is called.
Methods:
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
filesystem_mixin
¤
Filesystem Mixin to ease filesystem use.
Classes:
-
FilesystemMixin–Mixin providing filesystem operations through the filesystem strategy.
FilesystemMixin
¤
Mixin providing filesystem operations through the filesystem strategy.
This mixin wraps filesystem strategy calls to provide a cleaner API for file operations in trigger handlers.
Methods:
-
get_file–Retrieve a file by ID with the content.
-
upload_files–Upload files using the filesystem strategy.
get_file
async
staticmethod
¤
get_file(context: ModuleContext, file_id: str) -> FilesystemRecord
Retrieve a file by ID with the content.
Parameters:
-
(context¤ModuleContext) –Module context containing the filesystem strategy
-
(file_id¤str) –Unique identifier for the file
Returns:
-
FilesystemRecord–File object with metadata and optionally content
Raises:
-
FilesystemServiceError–If file retrieval fails
upload_files
async
staticmethod
¤
upload_files(
context: ModuleContext, files: list[Any]
) -> tuple[list[FilesystemRecord], int, int]
Upload files using the filesystem strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the filesystem strategy
-
(files¤list[Any]) –List of files to upload
Returns:
-
tuple[list[FilesystemRecord], int, int]–Tuple of (all_files, succeeded_files, failed_files)
Raises:
-
FilesystemServiceError–If upload operation fails
logger_mixin
¤
Logger Mixin to ease and merge every logs.
Classes:
-
LoggerMixin–Mixin providing callback operations through the callbacks strategy.
LoggerMixin
¤
Mixin providing callback operations through the callbacks strategy.
This mixin wraps callback strategy calls to provide a cleaner API for logging and messaging in trigger handlers.
Methods:
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
storage_mixin
¤
Storage Mixin to ease storage access in Triggers.
Classes:
-
StorageMixin–Mixin providing storage operations through the storage strategy.
StorageMixin
¤
Mixin providing storage operations through the storage strategy.
This mixin wraps storage strategy calls to provide a cleaner API for trigger handlers.
Methods:
-
read_storage–Read data from storage.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
models
¤
This package contains the models for DigitalKin.
Modules:
-
core–Core models.
-
events–Agent run event models for DigitalKin.
-
grpc_servers–Base gRPC server and client models.
-
module–This module contains the models for the modules.
-
services–This module contains the models for the services.
-
settings–This package contain settings of sdk.
Classes:
-
AgentRunEvent–Agent run event types.
-
BaseAgentRunEvent–Base class for all agent run events.
-
Module–Module model.
-
ModuleStatus–Possible module's state.
-
ReasoningCompletedEvent–Event emitted when a reasoning phase completes.
-
ReasoningContentDeltaEvent–Event emitted during extended thinking/reasoning phases.
-
ReasoningStartedEvent–Event emitted when a reasoning phase starts.
-
ReasoningStepEvent–Event emitted for intermediate reasoning steps.
-
RunCompletedEvent–Event emitted when an agent run completes successfully.
-
RunContentEvent–Event emitted when the agent produces content (text, reasoning, etc.).
-
RunErrorEvent–Event emitted when an agent run encounters an error.
-
RunStartedEvent–Event emitted when an agent run starts.
-
ToolCallCompletedEvent–Event emitted when a tool call completes successfully.
-
ToolCallErrorEvent–Event emitted when a tool call encounters an error.
-
ToolCallStartedEvent–Event emitted when a tool call starts.
-
ToolInfo–Information about a tool call.
AgentRunEvent
¤
flowchart TD
digitalkin.models.AgentRunEvent[AgentRunEvent]
click digitalkin.models.AgentRunEvent href "" "digitalkin.models.AgentRunEvent"
Agent run event types.
BaseAgentRunEvent
¤
flowchart TD
digitalkin.models.BaseAgentRunEvent[BaseAgentRunEvent]
click digitalkin.models.BaseAgentRunEvent href "" "digitalkin.models.BaseAgentRunEvent"
Base class for all agent run events.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
Module
¤
flowchart TD
digitalkin.models.Module[Module]
click digitalkin.models.Module href "" "digitalkin.models.Module"
Module model.
ModuleStatus
¤
flowchart TD
digitalkin.models.ModuleStatus[ModuleStatus]
click digitalkin.models.ModuleStatus href "" "digitalkin.models.ModuleStatus"
Possible module's state.
ReasoningCompletedEvent
¤
flowchart TD
digitalkin.models.ReasoningCompletedEvent[ReasoningCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningCompletedEvent
click digitalkin.models.ReasoningCompletedEvent href "" "digitalkin.models.ReasoningCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase completes.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningContentDeltaEvent
¤
flowchart TD
digitalkin.models.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningContentDeltaEvent
click digitalkin.models.ReasoningContentDeltaEvent href "" "digitalkin.models.ReasoningContentDeltaEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted during extended thinking/reasoning phases.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStartedEvent
¤
flowchart TD
digitalkin.models.ReasoningStartedEvent[ReasoningStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningStartedEvent
click digitalkin.models.ReasoningStartedEvent href "" "digitalkin.models.ReasoningStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStepEvent
¤
flowchart TD
digitalkin.models.ReasoningStepEvent[ReasoningStepEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ReasoningStepEvent
click digitalkin.models.ReasoningStepEvent href "" "digitalkin.models.ReasoningStepEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted for intermediate reasoning steps.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunCompletedEvent
¤
flowchart TD
digitalkin.models.RunCompletedEvent[RunCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunCompletedEvent
click digitalkin.models.RunCompletedEvent href "" "digitalkin.models.RunCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunContentEvent
¤
flowchart TD
digitalkin.models.RunContentEvent[RunContentEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunContentEvent
click digitalkin.models.RunContentEvent href "" "digitalkin.models.RunContentEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when the agent produces content (text, reasoning, etc.).
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunErrorEvent
¤
flowchart TD
digitalkin.models.RunErrorEvent[RunErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunErrorEvent
click digitalkin.models.RunErrorEvent href "" "digitalkin.models.RunErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunStartedEvent
¤
flowchart TD
digitalkin.models.RunStartedEvent[RunStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.RunStartedEvent
click digitalkin.models.RunStartedEvent href "" "digitalkin.models.RunStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallCompletedEvent
¤
flowchart TD
digitalkin.models.ToolCallCompletedEvent[ToolCallCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallCompletedEvent
click digitalkin.models.ToolCallCompletedEvent href "" "digitalkin.models.ToolCallCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallErrorEvent
¤
flowchart TD
digitalkin.models.ToolCallErrorEvent[ToolCallErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallErrorEvent
click digitalkin.models.ToolCallErrorEvent href "" "digitalkin.models.ToolCallErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallStartedEvent
¤
flowchart TD
digitalkin.models.ToolCallStartedEvent[ToolCallStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.ToolCallStartedEvent
click digitalkin.models.ToolCallStartedEvent href "" "digitalkin.models.ToolCallStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolInfo
¤
flowchart TD
digitalkin.models.ToolInfo[ToolInfo]
click digitalkin.models.ToolInfo href "" "digitalkin.models.ToolInfo"
Information about a tool call.
core
¤
Core models.
Modules:
-
job_manager_models–Job manager models.
-
task_monitor–Task monitoring models for signaling messages.
job_manager_models
¤
Job manager models.
Classes:
-
BackpressureStrategy–Backpressure strategy for module output queue writes.
-
JobManagerMode–Job manager mode.
BackpressureStrategy
¤
flowchart TD
digitalkin.models.core.job_manager_models.BackpressureStrategy[BackpressureStrategy]
click digitalkin.models.core.job_manager_models.BackpressureStrategy href "" "digitalkin.models.core.job_manager_models.BackpressureStrategy"
Backpressure strategy for module output queue writes.
JobManagerMode
¤
flowchart TD
digitalkin.models.core.job_manager_models.JobManagerMode[JobManagerMode]
click digitalkin.models.core.job_manager_models.JobManagerMode href "" "digitalkin.models.core.job_manager_models.JobManagerMode"
Job manager mode.
Methods:
-
__str__–Get the string representation of the job manager mode.
-
get_manager_class–Get the job manager class based on the mode.
__str__
¤
__str__() -> str
Get the string representation of the job manager mode.
Returns:
-
str(str) –job manager mode name.
get_manager_class
¤
get_manager_class() -> type[BaseJobManager]
Get the job manager class based on the mode.
Returns:
-
type(type[BaseJobManager]) –The job manager class.
task_monitor
¤
Task monitoring models for signaling messages.
Classes:
-
CancellationReason–Reason for task termination.
-
SignalMessage–Signal message model for task monitoring.
-
SignalType–Signal type enumeration.
CancellationReason
¤
flowchart TD
digitalkin.models.core.task_monitor.CancellationReason[CancellationReason]
click digitalkin.models.core.task_monitor.CancellationReason href "" "digitalkin.models.core.task_monitor.CancellationReason"
Reason for task termination.
SignalMessage
¤
flowchart TD
digitalkin.models.core.task_monitor.SignalMessage[SignalMessage]
click digitalkin.models.core.task_monitor.SignalMessage href "" "digitalkin.models.core.task_monitor.SignalMessage"
Signal message model for task monitoring.
SignalType
¤
flowchart TD
digitalkin.models.core.task_monitor.SignalType[SignalType]
click digitalkin.models.core.task_monitor.SignalType href "" "digitalkin.models.core.task_monitor.SignalType"
Signal type enumeration.
events
¤
Agent run event models for DigitalKin.
This module provides framework-agnostic event models for agent runs. These models can be used as a common interface across different AI frameworks.
Modules:
-
agent_events–Framework-agnostic agent run event models.
Classes:
-
AgentRunEvent–Agent run event types.
-
BaseAgentRunEvent–Base class for all agent run events.
-
CustomEvent–Event emitted for application-defined custom events.
-
ReasoningCompletedEvent–Event emitted when a reasoning phase completes.
-
ReasoningContentDeltaEvent–Event emitted during extended thinking/reasoning phases.
-
ReasoningStartedEvent–Event emitted when a reasoning phase starts.
-
ReasoningStepEvent–Event emitted for intermediate reasoning steps.
-
RunCompletedEvent–Event emitted when an agent run completes successfully.
-
RunContentEvent–Event emitted when the agent produces content (text, reasoning, etc.).
-
RunErrorEvent–Event emitted when an agent run encounters an error.
-
RunStartedEvent–Event emitted when an agent run starts.
-
TextMessageCompletedEvent–Event emitted when a text message sequence ends.
-
TextMessageStartedEvent–Event emitted when a new text message sequence begins.
-
ToolCallCompletedEvent–Event emitted when a tool call completes successfully.
-
ToolCallErrorEvent–Event emitted when a tool call encounters an error.
-
ToolCallStartedEvent–Event emitted when a tool call starts.
-
ToolInfo–Information about a tool call.
AgentRunEvent
¤
flowchart TD
digitalkin.models.events.AgentRunEvent[AgentRunEvent]
click digitalkin.models.events.AgentRunEvent href "" "digitalkin.models.events.AgentRunEvent"
Agent run event types.
BaseAgentRunEvent
¤
flowchart TD
digitalkin.models.events.BaseAgentRunEvent[BaseAgentRunEvent]
click digitalkin.models.events.BaseAgentRunEvent href "" "digitalkin.models.events.BaseAgentRunEvent"
Base class for all agent run events.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
CustomEvent
¤
flowchart TD
digitalkin.models.events.CustomEvent[CustomEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.CustomEvent
click digitalkin.models.events.CustomEvent href "" "digitalkin.models.events.CustomEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted for application-defined custom events.
Carries an application-specific name that discriminates the custom
event subtype and a free-form value payload for metadata transfer.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningCompletedEvent
¤
flowchart TD
digitalkin.models.events.ReasoningCompletedEvent[ReasoningCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningCompletedEvent
click digitalkin.models.events.ReasoningCompletedEvent href "" "digitalkin.models.events.ReasoningCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase completes.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningContentDeltaEvent
¤
flowchart TD
digitalkin.models.events.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningContentDeltaEvent
click digitalkin.models.events.ReasoningContentDeltaEvent href "" "digitalkin.models.events.ReasoningContentDeltaEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted during extended thinking/reasoning phases.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStartedEvent
¤
flowchart TD
digitalkin.models.events.ReasoningStartedEvent[ReasoningStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningStartedEvent
click digitalkin.models.events.ReasoningStartedEvent href "" "digitalkin.models.events.ReasoningStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStepEvent
¤
flowchart TD
digitalkin.models.events.ReasoningStepEvent[ReasoningStepEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ReasoningStepEvent
click digitalkin.models.events.ReasoningStepEvent href "" "digitalkin.models.events.ReasoningStepEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted for intermediate reasoning steps.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunCompletedEvent
¤
flowchart TD
digitalkin.models.events.RunCompletedEvent[RunCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunCompletedEvent
click digitalkin.models.events.RunCompletedEvent href "" "digitalkin.models.events.RunCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunContentEvent
¤
flowchart TD
digitalkin.models.events.RunContentEvent[RunContentEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunContentEvent
click digitalkin.models.events.RunContentEvent href "" "digitalkin.models.events.RunContentEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when the agent produces content (text, reasoning, etc.).
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunErrorEvent
¤
flowchart TD
digitalkin.models.events.RunErrorEvent[RunErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunErrorEvent
click digitalkin.models.events.RunErrorEvent href "" "digitalkin.models.events.RunErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunStartedEvent
¤
flowchart TD
digitalkin.models.events.RunStartedEvent[RunStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.RunStartedEvent
click digitalkin.models.events.RunStartedEvent href "" "digitalkin.models.events.RunStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
TextMessageCompletedEvent
¤
flowchart TD
digitalkin.models.events.TextMessageCompletedEvent[TextMessageCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.TextMessageCompletedEvent
click digitalkin.models.events.TextMessageCompletedEvent href "" "digitalkin.models.events.TextMessageCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a text message sequence ends.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
TextMessageStartedEvent
¤
flowchart TD
digitalkin.models.events.TextMessageStartedEvent[TextMessageStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.TextMessageStartedEvent
click digitalkin.models.events.TextMessageStartedEvent href "" "digitalkin.models.events.TextMessageStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a new text message sequence begins.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallCompletedEvent
¤
flowchart TD
digitalkin.models.events.ToolCallCompletedEvent[ToolCallCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallCompletedEvent
click digitalkin.models.events.ToolCallCompletedEvent href "" "digitalkin.models.events.ToolCallCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallErrorEvent
¤
flowchart TD
digitalkin.models.events.ToolCallErrorEvent[ToolCallErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallErrorEvent
click digitalkin.models.events.ToolCallErrorEvent href "" "digitalkin.models.events.ToolCallErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallStartedEvent
¤
flowchart TD
digitalkin.models.events.ToolCallStartedEvent[ToolCallStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.ToolCallStartedEvent
click digitalkin.models.events.ToolCallStartedEvent href "" "digitalkin.models.events.ToolCallStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolInfo
¤
flowchart TD
digitalkin.models.events.ToolInfo[ToolInfo]
click digitalkin.models.events.ToolInfo href "" "digitalkin.models.events.ToolInfo"
Information about a tool call.
agent_events
¤
Framework-agnostic agent run event models.
These models define a common interface for agent execution events that can be used across different AI frameworks (Agno, LangChain, custom agents, etc.).
Classes:
-
AgentRunEvent–Agent run event types.
-
BaseAgentRunEvent–Base class for all agent run events.
-
CustomEvent–Event emitted for application-defined custom events.
-
ReasoningCompletedEvent–Event emitted when a reasoning phase completes.
-
ReasoningContentDeltaEvent–Event emitted during extended thinking/reasoning phases.
-
ReasoningStartedEvent–Event emitted when a reasoning phase starts.
-
ReasoningStepEvent–Event emitted for intermediate reasoning steps.
-
RunCompletedEvent–Event emitted when an agent run completes successfully.
-
RunContentEvent–Event emitted when the agent produces content (text, reasoning, etc.).
-
RunErrorEvent–Event emitted when an agent run encounters an error.
-
RunStartedEvent–Event emitted when an agent run starts.
-
TextMessageCompletedEvent–Event emitted when a text message sequence ends.
-
TextMessageStartedEvent–Event emitted when a new text message sequence begins.
-
ToolCallCompletedEvent–Event emitted when a tool call completes successfully.
-
ToolCallErrorEvent–Event emitted when a tool call encounters an error.
-
ToolCallStartedEvent–Event emitted when a tool call starts.
-
ToolInfo–Information about a tool call.
AgentRunEvent
¤
flowchart TD
digitalkin.models.events.agent_events.AgentRunEvent[AgentRunEvent]
click digitalkin.models.events.agent_events.AgentRunEvent href "" "digitalkin.models.events.agent_events.AgentRunEvent"
Agent run event types.
BaseAgentRunEvent
¤
flowchart TD
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Base class for all agent run events.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
CustomEvent
¤
flowchart TD
digitalkin.models.events.agent_events.CustomEvent[CustomEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.CustomEvent
click digitalkin.models.events.agent_events.CustomEvent href "" "digitalkin.models.events.agent_events.CustomEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted for application-defined custom events.
Carries an application-specific name that discriminates the custom
event subtype and a free-form value payload for metadata transfer.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningCompletedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ReasoningCompletedEvent[ReasoningCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningCompletedEvent
click digitalkin.models.events.agent_events.ReasoningCompletedEvent href "" "digitalkin.models.events.agent_events.ReasoningCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase completes.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningContentDeltaEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ReasoningContentDeltaEvent[ReasoningContentDeltaEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningContentDeltaEvent
click digitalkin.models.events.agent_events.ReasoningContentDeltaEvent href "" "digitalkin.models.events.agent_events.ReasoningContentDeltaEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted during extended thinking/reasoning phases.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStartedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ReasoningStartedEvent[ReasoningStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningStartedEvent
click digitalkin.models.events.agent_events.ReasoningStartedEvent href "" "digitalkin.models.events.agent_events.ReasoningStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a reasoning phase starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ReasoningStepEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ReasoningStepEvent[ReasoningStepEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ReasoningStepEvent
click digitalkin.models.events.agent_events.ReasoningStepEvent href "" "digitalkin.models.events.agent_events.ReasoningStepEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted for intermediate reasoning steps.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunCompletedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.RunCompletedEvent[RunCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunCompletedEvent
click digitalkin.models.events.agent_events.RunCompletedEvent href "" "digitalkin.models.events.agent_events.RunCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunContentEvent
¤
flowchart TD
digitalkin.models.events.agent_events.RunContentEvent[RunContentEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunContentEvent
click digitalkin.models.events.agent_events.RunContentEvent href "" "digitalkin.models.events.agent_events.RunContentEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when the agent produces content (text, reasoning, etc.).
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunErrorEvent
¤
flowchart TD
digitalkin.models.events.agent_events.RunErrorEvent[RunErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunErrorEvent
click digitalkin.models.events.agent_events.RunErrorEvent href "" "digitalkin.models.events.agent_events.RunErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
RunStartedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.RunStartedEvent[RunStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.RunStartedEvent
click digitalkin.models.events.agent_events.RunStartedEvent href "" "digitalkin.models.events.agent_events.RunStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when an agent run starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
TextMessageCompletedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.TextMessageCompletedEvent[TextMessageCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.TextMessageCompletedEvent
click digitalkin.models.events.agent_events.TextMessageCompletedEvent href "" "digitalkin.models.events.agent_events.TextMessageCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a text message sequence ends.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
TextMessageStartedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.TextMessageStartedEvent[TextMessageStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.TextMessageStartedEvent
click digitalkin.models.events.agent_events.TextMessageStartedEvent href "" "digitalkin.models.events.agent_events.TextMessageStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a new text message sequence begins.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallCompletedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ToolCallCompletedEvent[ToolCallCompletedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallCompletedEvent
click digitalkin.models.events.agent_events.ToolCallCompletedEvent href "" "digitalkin.models.events.agent_events.ToolCallCompletedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call completes successfully.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallErrorEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ToolCallErrorEvent[ToolCallErrorEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallErrorEvent
click digitalkin.models.events.agent_events.ToolCallErrorEvent href "" "digitalkin.models.events.agent_events.ToolCallErrorEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call encounters an error.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolCallStartedEvent
¤
flowchart TD
digitalkin.models.events.agent_events.ToolCallStartedEvent[ToolCallStartedEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent[BaseAgentRunEvent]
digitalkin.models.events.agent_events.BaseAgentRunEvent --> digitalkin.models.events.agent_events.ToolCallStartedEvent
click digitalkin.models.events.agent_events.ToolCallStartedEvent href "" "digitalkin.models.events.agent_events.ToolCallStartedEvent"
click digitalkin.models.events.agent_events.BaseAgentRunEvent href "" "digitalkin.models.events.agent_events.BaseAgentRunEvent"
Event emitted when a tool call starts.
Classes:
-
Config–Pydantic configuration.
Config
¤
Pydantic configuration.
ToolInfo
¤
flowchart TD
digitalkin.models.events.agent_events.ToolInfo[ToolInfo]
click digitalkin.models.events.agent_events.ToolInfo href "" "digitalkin.models.events.agent_events.ToolInfo"
Information about a tool call.
grpc_servers
¤
Base gRPC server and client models.
Modules:
models
¤
Data models for gRPC server configurations.
Classes:
-
ChannelConfig–Base configuration for gRPC channels.
-
ClientConfig–Base configuration for gRPC clients.
-
ClientCredentials–Model for client credentials in secure mode.
-
GrpcCompression–gRPC compression algorithm.
-
RetryPolicy–gRPC retry policy configuration for resilient connections.
ChannelConfig
¤
flowchart TD
digitalkin.models.grpc_servers.models.ChannelConfig[ChannelConfig]
click digitalkin.models.grpc_servers.models.ChannelConfig href "" "digitalkin.models.grpc_servers.models.ChannelConfig"
Base configuration for gRPC channels.
Attributes:
-
host(str) –Host address
-
port(int) –Port to listen on
-
mode(ControlFlow) –communication operation mode (sync/async)
-
security(SecurityMode) –Security mode (secure/insecure)
-
credentials(SecurityMode) –Client credentials for secure mode
Methods:
-
validate_port–Validate that the port is in a valid range.
ClientConfig
¤
flowchart TD
digitalkin.models.grpc_servers.models.ClientConfig[ClientConfig]
digitalkin.models.grpc_servers.models.ChannelConfig[ChannelConfig]
digitalkin.models.grpc_servers.models.ChannelConfig --> digitalkin.models.grpc_servers.models.ClientConfig
click digitalkin.models.grpc_servers.models.ClientConfig href "" "digitalkin.models.grpc_servers.models.ClientConfig"
click digitalkin.models.grpc_servers.models.ChannelConfig href "" "digitalkin.models.grpc_servers.models.ChannelConfig"
Base configuration for gRPC clients.
Attributes:
-
host(str) –Host address to bind the client to
-
port(int) –Port to listen on
-
mode(ControlFlow) –Client operation mode (sync/async)
-
security(SecurityMode) –Security mode (secure/insecure)
-
credentials(ClientCredentials | None) –Client credentials for secure mode
-
channel_options(list[tuple[str, Any]]) –Additional channel options
-
retry_policy(RetryPolicy) –Retry policy for failed RPCs
-
compression(GrpcCompression) –gRPC compression algorithm for channel-level compression
Methods:
-
validate_credentials–Validate that credentials are provided when in secure mode.
-
validate_port–Validate that the port is in a valid range.
grpc_options
property
¤
validate_credentials
classmethod
¤
validate_credentials(
v: ClientCredentials | None, info: ValidationInfo
) -> ClientCredentials | None
Validate that credentials are provided when in secure mode.
Parameters:
-
(v¤ClientCredentials | None) –The credentials value
-
(info¤ValidationInfo) –ValidationInfo containing other field values
Returns:
-
ClientCredentials | None–The validated credentials
Raises:
-
ConfigurationError–If credentials are missing in secure mode
ClientCredentials
¤
flowchart TD
digitalkin.models.grpc_servers.models.ClientCredentials[ClientCredentials]
click digitalkin.models.grpc_servers.models.ClientCredentials href "" "digitalkin.models.grpc_servers.models.ClientCredentials"
Model for client credentials in secure mode.
Attributes:
-
root_cert_path(Path) –path to the root certificate
-
client_key_path(Path | None) –Path to the client private key
-
client_cert_path(Path | None) –Path to the client certificate
Methods:
-
check_path_exists–Validate that the file path exists.
GrpcCompression
¤
flowchart TD
digitalkin.models.grpc_servers.models.GrpcCompression[GrpcCompression]
click digitalkin.models.grpc_servers.models.GrpcCompression href "" "digitalkin.models.grpc_servers.models.GrpcCompression"
gRPC compression algorithm.
Attributes:
-
NONE–No compression
-
GZIP–Gzip compression
-
DEFLATE–Deflate compression
Methods:
-
to_grpc–Convert to grpc.Compression enum.
to_grpc
¤
to_grpc() -> Compression
Convert to grpc.Compression enum.
Returns:
-
Compression–The corresponding grpc.Compression value.
RetryPolicy
¤
flowchart TD
digitalkin.models.grpc_servers.models.RetryPolicy[RetryPolicy]
click digitalkin.models.grpc_servers.models.RetryPolicy href "" "digitalkin.models.grpc_servers.models.RetryPolicy"
gRPC retry policy configuration for resilient connections.
Attributes:
-
max_attempts(int) –Maximum retry attempts including the original call
-
initial_backoff(str) –Initial backoff duration (e.g., "0.1s")
-
max_backoff(str) –Maximum backoff duration (e.g., "10s")
-
backoff_multiplier(float) –Multiplier for exponential backoff
-
retryable_status_codes(list[str]) –gRPC status codes that trigger retry
Methods:
-
to_service_config_json–Serialize to gRPC service config JSON string.
types
¤
Type definitions for gRPC utilities.
Classes:
-
ServiceDescriptor–Protocol for gRPC service descriptors.
-
ServiceObject–Protocol for individual services in a gRPC descriptor.
ServiceDescriptor
¤
flowchart TD
digitalkin.models.grpc_servers.types.ServiceDescriptor[ServiceDescriptor]
click digitalkin.models.grpc_servers.types.ServiceDescriptor href "" "digitalkin.models.grpc_servers.types.ServiceDescriptor"
Protocol for gRPC service descriptors.
ServiceObject
¤
flowchart TD
digitalkin.models.grpc_servers.types.ServiceObject[ServiceObject]
click digitalkin.models.grpc_servers.types.ServiceObject href "" "digitalkin.models.grpc_servers.types.ServiceObject"
Protocol for individual services in a gRPC descriptor.
module
¤
This module contains the models for the modules.
Modules:
-
ag_ui–Output model for the Template module.
-
base_types–Base types for module models.
-
module–Module model.
-
module_context–Define the module context used in the triggers.
-
module_types–Types for module models - backward compatibility re-exports.
-
request_metadata–Immutable container for gRPC request metadata (headers).
-
select_schema–SelectSchema for trigger selection UI generation.
-
setup_types–Setup model types with dynamic schema resolution and tool reference support.
-
tool_cache–Tool cache for resolved tool references.
-
tool_reference–Tool reference types for module configuration.
-
utility–Utility protocols for SDK-provided functionality.
Classes:
-
DataModel–Base definition of input/output model showing mandatory root fields.
-
DataTrigger–Defines the root input/output model exposing the protocol.
-
EndOfStreamOutput–Signal that the stream has ended.
-
ModuleContext–ModuleContext provides a container for strategies and resources used by a module.
-
ModuleStartInfoOutput–Output sent when module starts with execution context.
-
RequestMetadata–Immutable container for gRPC request metadata (headers).
-
SelectSchema–Base class for generating trigger selection schema.
-
SetupModel–Base setup model with dynamic schema and tool cache support.
-
ToolCache–Registry cache storing resolved tool references by setup field name.
-
ToolDefinition–Complete definition of an LLM tool with resolved JSON Schema parameters.
-
ToolModuleInfo–Module info for tool modules.
-
ToolReference–Tool selection containing setup IDs and trigger filters.
-
ToolSelection–Single tool selection with trigger filtering.
-
UtilityProtocol–Base class for SDK-provided utility protocols.
-
UtilityRegistry–Registry for SDK-provided built-in triggers.
Functions:
-
tool_reference_input–Create ToolReferenceInput type with schema options and validation.
DataModel
¤
flowchart TD
digitalkin.models.module.DataModel[DataModel]
click digitalkin.models.module.DataModel href "" "digitalkin.models.module.DataModel"
Base definition of input/output model showing mandatory root fields.
The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.
Example
class ModuleInput(DataModel): root: FileInput | MessageInput
-
digitalkin
DataTrigger
¤
flowchart TD
digitalkin.models.module.DataTrigger[DataTrigger]
click digitalkin.models.module.DataTrigger href "" "digitalkin.models.module.DataTrigger"
Defines the root input/output model exposing the protocol.
The mandatory protocol is important to define the module beahvior following the user or agent input/output.
Example
class MyInput(DataModel): root: DataTrigger user_define_data: Any
Usage¤
my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message
EndOfStreamOutput
¤
flowchart TD
digitalkin.models.module.EndOfStreamOutput[EndOfStreamOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.EndOfStreamOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.EndOfStreamOutput href "" "digitalkin.models.module.EndOfStreamOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Signal that the stream has ended.
ModuleContext
¤
ModuleContext(
agent: AgentStrategy,
communication: CommunicationStrategy,
cost: CostStrategy,
filesystem: FilesystemStrategy,
identity: IdentityStrategy,
registry: RegistryStrategy,
snapshot: SnapshotStrategy,
storage: StorageStrategy,
task_manager: TaskManagerStrategy,
user_profile: UserProfileStrategy,
session: dict[str, Any],
metadata: dict[str, Any] | None = None,
helpers: dict[str, Any] | None = None,
callbacks: dict[str, Any] | None = None,
tool_cache: ToolCache | None = None,
request_metadata: dict[str, str] | None = None,
)
ModuleContext provides a container for strategies and resources used by a module.
This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.
Parameters:
-
(agent¤AgentStrategy) –AgentStrategy.
-
(communication¤CommunicationStrategy) –CommunicationStrategy.
-
(cost¤CostStrategy) –CostStrategy.
-
(filesystem¤FilesystemStrategy) –FilesystemStrategy.
-
(identity¤IdentityStrategy) –IdentityStrategy.
-
(registry¤RegistryStrategy) –RegistryStrategy.
-
(snapshot¤SnapshotStrategy) –SnapshotStrategy.
-
(storage¤StorageStrategy) –StorageStrategy.
-
(task_manager¤TaskManagerStrategy) –TaskManagerStrategy.
-
(user_profile¤UserProfileStrategy) –UserProfileStrategy.
-
(metadata¤dict[str, Any] | None, default:None) –dict defining differents Module metadata.
-
(helpers¤dict[str, Any] | None, default:None) –dict different user defined helpers.
-
(session¤dict[str, Any]) –dict referring the session IDs or informations.
-
(callbacks¤dict[str, Any] | None, default:None) –Functions allowing user to agent interaction.
-
(tool_cache¤ToolCache | None, default:None) –ToolCache with pre-resolved tool references from setup.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
-
digitalkin-
ArchetypeModule -
ToolModule -
TriggerHandler -
communityagno -
mixins-
AgUiMixinsend_message -
BaseMixin -
CostMixin -
FilesystemMixin -
LoggerMixin -
StorageMixin -
agui_mixinAgUiMixinsend_message -
base_mixinBaseMixin -
callback_mixinUserMessageMixinsend_message -
chat_history_mixinChatHistoryMixin -
cost_mixinCostMixin -
file_history_mixinFileHistoryMixin -
filesystem_mixinFilesystemMixin -
logger_mixinLoggerMixin -
storage_mixinStorageMixin
-
-
modules -
utilspackage_discoverModuleDiscovererinit_handlers
-
Methods:
-
cleanup–Close all service strategies and release their resources.
-
create_openai_style_tools–Create OpenAI-style function calling schemas for a tool module.
-
create_tool_functions–Create tool functions for all protocols in a tool setup.
-
get_module_schemas_by_id–Get module schemas by ID, discovering address/port from registry.
create_openai_style_tools
¤
Create OpenAI-style function calling schemas for a tool module.
Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.
Parameters:
Returns:
create_tool_functions
¤
create_tool_functions(
slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]
Create tool functions for all protocols in a tool setup.
Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.
This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.
Parameters:
Returns:
-
list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]–List of (ToolDefinition, async_generator_function) tuples. Empty if not found.
ModuleStartInfoOutput
¤
flowchart TD
digitalkin.models.module.ModuleStartInfoOutput[ModuleStartInfoOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.ModuleStartInfoOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.ModuleStartInfoOutput href "" "digitalkin.models.module.ModuleStartInfoOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Output sent when module starts with execution context.
This protocol is sent as the first message when a module starts, providing the client with essential execution context information.
RequestMetadata
¤
Immutable container for gRPC request metadata (headers).
Provides typed access to common auth headers and raw access to all metadata.
Filters out gRPC-reserved keys (prefixed with grpc-).
Example::
metadata = RequestMetadata({"authorization": "Bearer eyJ...", "x-tenant-id": "t-123"})
token = metadata.bearer_token # "eyJ..."
tenant = metadata.get("x-tenant-id") # "t-123"
Parameters:
-
(raw¤dict[str, str] | None, default:None) –Dictionary of metadata key-value pairs. Keys prefixed with
grpc-are filtered out.
Methods:
-
__bool__–Return True if metadata is non-empty.
-
__contains__–Check if a metadata key exists.
-
__getitem__–Get a metadata value by key.
-
__repr__–Return a string representation (sensitive values masked).
-
get–Get any metadata value by key.
-
to_dict–Return a copy of the raw metadata dictionary.
-
to_grpc_metadata–Convert to gRPC metadata format for forwarding.
Attributes:
-
api_key(str | None) –Get the
x-api-keyheader value. -
authorization(str | None) –Get the Authorization header value (e.g.,
Bearer <token>). -
bearer_token(str | None) –Extract the bearer token from the Authorization header.
authorization
property
¤
authorization: str | None
Get the Authorization header value (e.g., Bearer <token>).
bearer_token
property
¤
bearer_token: str | None
Extract the bearer token from the Authorization header.
Returns:
-
str | None–The token string if the Authorization header starts with
Bearer, otherwise None.
__contains__
¤
__getitem__
¤
get
¤
SelectSchema
¤
flowchart TD
digitalkin.models.module.SelectSchema[SelectSchema]
click digitalkin.models.module.SelectSchema href "" "digitalkin.models.module.SelectSchema"
Base class for generating trigger selection schema.
Subclass and add boolean fields to customize the selection UI.
If no fields are defined, schema is auto-generated from registered protocols.
Set select_format = None in your module to disable.
Example
class MySelectSchema(SelectSchema): message: bool = Field(default=True, title="Message", description="Process messages") file: bool = Field(default=False, title="File", description="Process files")
Methods:
-
build–Build the select schema.
build
classmethod
¤
Build the select schema.
If the subclass has user-defined fields, uses those. Otherwise, auto-generates from protocols_info.
Parameters:
Returns:
SetupModel
¤
flowchart TD
digitalkin.models.module.SetupModel[SetupModel]
click digitalkin.models.module.SetupModel href "" "digitalkin.models.module.SetupModel"
Base setup model with dynamic schema and tool cache support.
Methods:
-
build_tool_cache–Build tool cache, resolving uncached tools via registry.
-
get_clean_model–Build filtered model based on json_schema_extra metadata.
build_tool_cache
async
¤
build_tool_cache(
registry: RegistryStrategy | None = None,
communication: CommunicationStrategy | None = None,
) -> ToolCache
Build tool cache, resolving uncached tools via registry.
Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.
Parameters:
-
(registry¤RegistryStrategy | None, default:None) –Registry service for resolving uncached tools.
-
(communication¤CommunicationStrategy | None, default:None) –Communication service for module schemas.
Returns:
-
ToolCache–ToolCache with resolved tool entries.
get_clean_model
async
classmethod
¤
get_clean_model(
*, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]
Build filtered model based on json_schema_extra metadata.
Parameters:
-
(config_fields¤bool) –Include fields with json_schema_extra["config"] = True.
-
(hidden_fields¤bool) –Include fields with json_schema_extra["ui:widget"] = "hidden".
-
(force¤bool, default:False) –Refresh dynamic schema fields by calling providers.
Returns:
-
type[SetupModelT]–New BaseModel subclass with filtered fields.
ToolCache
¤
flowchart TD
digitalkin.models.module.ToolCache[ToolCache]
click digitalkin.models.module.ToolCache href "" "digitalkin.models.module.ToolCache"
Registry cache storing resolved tool references by setup field name.
Methods:
-
add–Add a tool to the cache.
-
clear–Clear all cache entries.
-
get–Get a tool from cache, optionally querying registry on miss.
-
list_tools–List all cached tool names.
add
¤
add(tool_module_info: ToolModuleInfo) -> None
Add a tool to the cache.
Parameters:
-
(tool_module_info¤ToolModuleInfo) –Resolved tool module information.
get
¤
get(setup_id: str) -> ToolModuleInfo | None
Get a tool from cache, optionally querying registry on miss.
Parameters:
Returns:
-
ToolModuleInfo | None–ToolModuleInfo if found, None otherwise.
ToolDefinition
¤
flowchart TD
digitalkin.models.module.ToolDefinition[ToolDefinition]
click digitalkin.models.module.ToolDefinition href "" "digitalkin.models.module.ToolDefinition"
Complete definition of an LLM tool with resolved JSON Schema parameters.
Attributes:
-
name(str) –Tool name (from protocol const or trigger class name).
-
description(str) –Tool description (from trigger docstring).
-
parameters_schema(dict[str, Any]) –JSON Schema object describing the tool's parameters.
ToolModuleInfo
¤
flowchart TD
digitalkin.models.module.ToolModuleInfo[ToolModuleInfo]
digitalkin.models.services.registry.ModuleInfo[ModuleInfo]
digitalkin.models.services.registry.ModuleInfo --> digitalkin.models.module.ToolModuleInfo
click digitalkin.models.module.ToolModuleInfo href "" "digitalkin.models.module.ToolModuleInfo"
click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
Module info for tool modules.
Attributes:
ToolReference
¤
flowchart TD
digitalkin.models.module.ToolReference[ToolReference]
click digitalkin.models.module.ToolReference href "" "digitalkin.models.module.ToolReference"
Tool selection containing setup IDs and trigger filters.
Methods:
-
resolve–Resolve selected tools using the registry.
resolve
async
¤
resolve(
registry: RegistryStrategy, communication: CommunicationStrategy
) -> list[ToolModuleInfo]
Resolve selected tools using the registry.
Each tool resolution is bounded by DIGITALKIN_TOOL_RESOLVE_TIMEOUT (default 10s).
Parameters:
-
(registry¤RegistryStrategy) –Registry service for module discovery.
-
(communication¤CommunicationStrategy) –Communication service for module schemas.
Returns:
-
list[ToolModuleInfo]–List of ToolModuleInfo for resolved tools, filtered by enabled triggers.
ToolSelection
¤
flowchart TD
digitalkin.models.module.ToolSelection[ToolSelection]
click digitalkin.models.module.ToolSelection href "" "digitalkin.models.module.ToolSelection"
Single tool selection with trigger filtering.
UtilityProtocol
¤
flowchart TD
digitalkin.models.module.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.UtilityProtocol
click digitalkin.models.module.UtilityProtocol href "" "digitalkin.models.module.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Base class for SDK-provided utility protocols.
All SDK utility protocols inherit from this class to enable: - Easy identification of SDK vs user-defined protocols - Auto-injection capability - Consistent behavior across the SDK
UtilityRegistry
¤
Registry for SDK-provided built-in triggers.
Example
builtin_triggers = UtilityRegistry.get_builtin_triggers()
Methods:
-
get_builtin_triggers–Get all SDK-provided built-in trigger handlers.
tool_reference_input
¤
tool_reference_input(
setup_ids: list[str] | None = None,
module_ids: list[str] | None = None,
tag_ids: list[str] | None = None,
categories: list[str] | None = None,
max_tools: int = 0,
min_tools: int = 0,
) -> type[ToolReference]
Create ToolReferenceInput type with schema options and validation.
Parameters:
-
(setup_ids¤list[str] | None, default:None) –Setup IDs for the user to choose from.
-
(module_ids¤list[str] | None, default:None) –Module IDs for the user to choose from.
-
(tag_ids¤list[str] | None, default:None) –Tag IDs for the user to choose from.
-
(categories¤list[str] | None, default:None) –Categories for the user to choose from.
-
(max_tools¤int, default:0) –Maximum tools allowed. 0 for unlimited.
-
(min_tools¤int, default:0) –Minimum tools required. 0 for no minimum.
Returns:
-
type[ToolReference]–Annotated type for use in Pydantic models.
ag_ui
¤
Output model for the Template module.
Classes:
-
AgUiActivityDeltaOutput–AG-UI ActivityDelta event - JSON Patch delta for an activity message.
-
AgUiActivitySnapshotOutput–AG-UI ActivitySnapshot event - full activity message snapshot.
-
AgUiCustomEventOutput–AG-UI CustomEvent event - carries an application-defined custom event.
-
AgUiDataTrigger–DataTrigger subclass that serializes wrapper fields as camelCase.
-
AgUiMessagesSnapshotOutput–AG-UI MessagesSnapshot event - full conversation messages snapshot.
-
AgUiOutput–Output model for the Template module with discriminated union.
-
AgUiRawEventOutput–AG-UI RawEvent event - passes through a raw/untyped event payload.
-
AgUiReasoningEncryptedValueOutput–AG-UI ReasoningEncryptedValue event - carries an encrypted reasoning value.
-
AgUiReasoningEndOutput–AG-UI ReasoningEnd event - signals end of a reasoning phase.
-
AgUiReasoningMessageChunkOutput–AG-UI ReasoningMessageChunk event - aggregated reasoning message chunk.
-
AgUiReasoningMessageContentOutput–AG-UI ReasoningMessageContent event - carries a reasoning content delta.
-
AgUiReasoningMessageEndOutput–AG-UI ReasoningMessageEnd event - signals end of a reasoning message.
-
AgUiReasoningMessageStartOutput–AG-UI ReasoningMessageStart event - signals start of a reasoning message.
-
AgUiReasoningStartOutput–AG-UI ReasoningStart event - signals start of a reasoning phase.
-
AgUiRunErrorOutput–AG-UI RunError event - signals that a run encountered an error.
-
AgUiRunFinishedOutput–AG-UI RunFinished event - signals that an agent run has completed.
-
AgUiRunStartedOutput–AG-UI RunStarted event - signals that an agent run has begun.
-
AgUiStateDeltaOutput–AG-UI StateDelta event - JSON Patch (RFC 6902) operations on agent state.
-
AgUiStateSnapshotOutput–AG-UI StateSnapshot event - full agent state snapshot.
-
AgUiStepFinishedOutput–AG-UI StepFinished event - signals completion of a named agent step.
-
AgUiStepStartedOutput–AG-UI StepStarted event - signals start of a named agent step.
-
AgUiTextMessageChunkOutput–AG-UI TextMessageChunk event - aggregated text message chunk.
-
AgUiTextMessageContentOutput–AG-UI TextMessageContent event - carries a text delta chunk.
-
AgUiTextMessageEndOutput–AG-UI TextMessageEnd event - signals end of a text message.
-
AgUiTextMessageStartOutput–AG-UI TextMessageStart event - signals start of a text message.
-
AgUiThinkingEndOutput–AG-UI ThinkingEnd event - signals end of a high-level thinking step.
-
AgUiThinkingStartOutput–AG-UI ThinkingStart event - signals start of a high-level thinking step.
-
AgUiThinkingTextMessageContentOutput–AG-UI ThinkingTextMessageContent event - carries a thinking text delta chunk.
-
AgUiThinkingTextMessageEndOutput–AG-UI ThinkingTextMessageEnd event - signals end of internal thinking.
-
AgUiThinkingTextMessageStartOutput–AG-UI ThinkingTextMessageStart event - signals start of internal thinking.
-
AgUiToolCallArgsOutput–AG-UI ToolCallArgs event - carries streamed tool call arguments delta.
-
AgUiToolCallChunkOutput–AG-UI ToolCallChunk event - aggregated tool call chunk.
-
AgUiToolCallEndOutput–AG-UI ToolCallEnd event - signals end of tool call argument streaming.
-
AgUiToolCallResultOutput–AG-UI ToolCallResult event - carries the result of a completed tool call.
-
AgUiToolCallStartOutput–AG-UI ToolCallStart event - signals start of a tool invocation.
AgUiActivityDeltaOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput[AgUiActivityDeltaOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput href "" "digitalkin.models.module.ag_ui.AgUiActivityDeltaOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ActivityDelta event - JSON Patch delta for an activity message.
AgUiActivitySnapshotOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput[AgUiActivitySnapshotOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiActivitySnapshotOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ActivitySnapshot event - full activity message snapshot.
AgUiCustomEventOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiCustomEventOutput[AgUiCustomEventOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiCustomEventOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiCustomEventOutput href "" "digitalkin.models.module.ag_ui.AgUiCustomEventOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI CustomEvent event - carries an application-defined custom event.
AgUiDataTrigger
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
DataTrigger subclass that serializes wrapper fields as camelCase.
AG-UI events must be serialized with camelCase field names. Since the SDK
calls model_dump(mode="json") without by_alias=True, we define
camelCase aliases here and activate them via TemplateOutput.model_dump.
AgUiMessagesSnapshotOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput[AgUiMessagesSnapshotOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiMessagesSnapshotOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI MessagesSnapshot event - full conversation messages snapshot.
AgUiOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiOutput[AgUiOutput]
digitalkin.models.module.base_types.DataModel[DataModel]
digitalkin.models.module.base_types.DataModel --> digitalkin.models.module.ag_ui.AgUiOutput
click digitalkin.models.module.ag_ui.AgUiOutput href "" "digitalkin.models.module.ag_ui.AgUiOutput"
click digitalkin.models.module.base_types.DataModel href "" "digitalkin.models.module.base_types.DataModel"
Output model for the Template module with discriminated union.
Methods:
-
model_dump–Serialize with camelCase aliases and exclude None fields by default.
AgUiRawEventOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiRawEventOutput[AgUiRawEventOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRawEventOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiRawEventOutput href "" "digitalkin.models.module.ag_ui.AgUiRawEventOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI RawEvent event - passes through a raw/untyped event payload.
AgUiReasoningEncryptedValueOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput[AgUiReasoningEncryptedValueOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningEncryptedValueOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningEncryptedValue event - carries an encrypted reasoning value.
AgUiReasoningEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningEndOutput[AgUiReasoningEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningEndOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningEnd event - signals end of a reasoning phase.
AgUiReasoningMessageChunkOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput[AgUiReasoningMessageChunkOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageChunkOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningMessageChunk event - aggregated reasoning message chunk.
AgUiReasoningMessageContentOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput[AgUiReasoningMessageContentOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageContentOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningMessageContent event - carries a reasoning content delta.
AgUiReasoningMessageEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput[AgUiReasoningMessageEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningMessageEnd event - signals end of a reasoning message.
AgUiReasoningMessageStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput[AgUiReasoningMessageStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningMessageStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningMessageStart event - signals start of a reasoning message.
AgUiReasoningStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiReasoningStartOutput[AgUiReasoningStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiReasoningStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiReasoningStartOutput href "" "digitalkin.models.module.ag_ui.AgUiReasoningStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ReasoningStart event - signals start of a reasoning phase.
AgUiRunErrorOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiRunErrorOutput[AgUiRunErrorOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunErrorOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiRunErrorOutput href "" "digitalkin.models.module.ag_ui.AgUiRunErrorOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI RunError event - signals that a run encountered an error.
AgUiRunFinishedOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiRunFinishedOutput[AgUiRunFinishedOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunFinishedOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiRunFinishedOutput href "" "digitalkin.models.module.ag_ui.AgUiRunFinishedOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI RunFinished event - signals that an agent run has completed.
AgUiRunStartedOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiRunStartedOutput[AgUiRunStartedOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiRunStartedOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiRunStartedOutput href "" "digitalkin.models.module.ag_ui.AgUiRunStartedOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI RunStarted event - signals that an agent run has begun.
AgUiStateDeltaOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiStateDeltaOutput[AgUiStateDeltaOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStateDeltaOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiStateDeltaOutput href "" "digitalkin.models.module.ag_ui.AgUiStateDeltaOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI StateDelta event - JSON Patch (RFC 6902) operations on agent state.
AgUiStateSnapshotOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput[AgUiStateSnapshotOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput href "" "digitalkin.models.module.ag_ui.AgUiStateSnapshotOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI StateSnapshot event - full agent state snapshot.
AgUiStepFinishedOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiStepFinishedOutput[AgUiStepFinishedOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStepFinishedOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiStepFinishedOutput href "" "digitalkin.models.module.ag_ui.AgUiStepFinishedOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI StepFinished event - signals completion of a named agent step.
AgUiStepStartedOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiStepStartedOutput[AgUiStepStartedOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiStepStartedOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiStepStartedOutput href "" "digitalkin.models.module.ag_ui.AgUiStepStartedOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI StepStarted event - signals start of a named agent step.
AgUiTextMessageChunkOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput[AgUiTextMessageChunkOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageChunkOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI TextMessageChunk event - aggregated text message chunk.
AgUiTextMessageContentOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput[AgUiTextMessageContentOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageContentOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI TextMessageContent event - carries a text delta chunk.
AgUiTextMessageEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput[AgUiTextMessageEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI TextMessageEnd event - signals end of a text message.
AgUiTextMessageStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput[AgUiTextMessageStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiTextMessageStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI TextMessageStart event - signals start of a text message.
AgUiThinkingEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiThinkingEndOutput[AgUiThinkingEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiThinkingEndOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ThinkingEnd event - signals end of a high-level thinking step.
AgUiThinkingStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiThinkingStartOutput[AgUiThinkingStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiThinkingStartOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ThinkingStart event - signals start of a high-level thinking step.
AgUiThinkingTextMessageContentOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput[AgUiThinkingTextMessageContentOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageContentOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ThinkingTextMessageContent event - carries a thinking text delta chunk.
AgUiThinkingTextMessageEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput[AgUiThinkingTextMessageEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ThinkingTextMessageEnd event - signals end of internal thinking.
AgUiThinkingTextMessageStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput[AgUiThinkingTextMessageStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput href "" "digitalkin.models.module.ag_ui.AgUiThinkingTextMessageStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ThinkingTextMessageStart event - signals start of internal thinking.
AgUiToolCallArgsOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput[AgUiToolCallArgsOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallArgsOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ToolCallArgs event - carries streamed tool call arguments delta.
AgUiToolCallChunkOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput[AgUiToolCallChunkOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallChunkOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ToolCallChunk event - aggregated tool call chunk.
AgUiToolCallEndOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiToolCallEndOutput[AgUiToolCallEndOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallEndOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiToolCallEndOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallEndOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ToolCallEnd event - signals end of tool call argument streaming.
AgUiToolCallResultOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiToolCallResultOutput[AgUiToolCallResultOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallResultOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiToolCallResultOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallResultOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ToolCallResult event - carries the result of a completed tool call.
AgUiToolCallStartOutput
¤
flowchart TD
digitalkin.models.module.ag_ui.AgUiToolCallStartOutput[AgUiToolCallStartOutput]
digitalkin.models.module.ag_ui.AgUiDataTrigger[AgUiDataTrigger]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.ag_ui.AgUiDataTrigger --> digitalkin.models.module.ag_ui.AgUiToolCallStartOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.ag_ui.AgUiDataTrigger
click digitalkin.models.module.ag_ui.AgUiToolCallStartOutput href "" "digitalkin.models.module.ag_ui.AgUiToolCallStartOutput"
click digitalkin.models.module.ag_ui.AgUiDataTrigger href "" "digitalkin.models.module.ag_ui.AgUiDataTrigger"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
AG-UI ToolCallStart event - signals start of a tool invocation.
base_types
¤
Base types for module models.
Classes:
-
DataModel–Base definition of input/output model showing mandatory root fields.
-
DataTrigger–Defines the root input/output model exposing the protocol.
DataModel
¤
flowchart TD
digitalkin.models.module.base_types.DataModel[DataModel]
click digitalkin.models.module.base_types.DataModel href "" "digitalkin.models.module.base_types.DataModel"
Base definition of input/output model showing mandatory root fields.
The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.
Example
class ModuleInput(DataModel): root: FileInput | MessageInput
-
digitalkin
DataTrigger
¤
flowchart TD
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Defines the root input/output model exposing the protocol.
The mandatory protocol is important to define the module beahvior following the user or agent input/output.
Example
class MyInput(DataModel): root: DataTrigger user_define_data: Any
Usage¤
my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message
module
¤
Module model.
Classes:
-
Module–Module model.
-
ModuleCodeModel–typed error/code model.
-
ModuleStatus–Possible module's state.
Module
¤
flowchart TD
digitalkin.models.module.module.Module[Module]
click digitalkin.models.module.module.Module href "" "digitalkin.models.module.module.Module"
Module model.
ModuleCodeModel
¤
flowchart TD
digitalkin.models.module.module.ModuleCodeModel[ModuleCodeModel]
click digitalkin.models.module.module.ModuleCodeModel href "" "digitalkin.models.module.module.ModuleCodeModel"
typed error/code model.
ModuleStatus
¤
flowchart TD
digitalkin.models.module.module.ModuleStatus[ModuleStatus]
click digitalkin.models.module.module.ModuleStatus href "" "digitalkin.models.module.module.ModuleStatus"
Possible module's state.
module_context
¤
Define the module context used in the triggers.
Classes:
-
ModuleContext–ModuleContext provides a container for strategies and resources used by a module.
-
Session–Session data container with mandatory setup_id and mission_id.
ModuleContext
¤
ModuleContext(
agent: AgentStrategy,
communication: CommunicationStrategy,
cost: CostStrategy,
filesystem: FilesystemStrategy,
identity: IdentityStrategy,
registry: RegistryStrategy,
snapshot: SnapshotStrategy,
storage: StorageStrategy,
task_manager: TaskManagerStrategy,
user_profile: UserProfileStrategy,
session: dict[str, Any],
metadata: dict[str, Any] | None = None,
helpers: dict[str, Any] | None = None,
callbacks: dict[str, Any] | None = None,
tool_cache: ToolCache | None = None,
request_metadata: dict[str, str] | None = None,
)
ModuleContext provides a container for strategies and resources used by a module.
This context object is designed to be passed to module components, providing them with access to shared strategies and resources. Additional attributes may be set dynamically.
Parameters:
-
(agent¤AgentStrategy) –AgentStrategy.
-
(communication¤CommunicationStrategy) –CommunicationStrategy.
-
(cost¤CostStrategy) –CostStrategy.
-
(filesystem¤FilesystemStrategy) –FilesystemStrategy.
-
(identity¤IdentityStrategy) –IdentityStrategy.
-
(registry¤RegistryStrategy) –RegistryStrategy.
-
(snapshot¤SnapshotStrategy) –SnapshotStrategy.
-
(storage¤StorageStrategy) –StorageStrategy.
-
(task_manager¤TaskManagerStrategy) –TaskManagerStrategy.
-
(user_profile¤UserProfileStrategy) –UserProfileStrategy.
-
(metadata¤dict[str, Any] | None, default:None) –dict defining differents Module metadata.
-
(helpers¤dict[str, Any] | None, default:None) –dict different user defined helpers.
-
(session¤dict[str, Any]) –dict referring the session IDs or informations.
-
(callbacks¤dict[str, Any] | None, default:None) –Functions allowing user to agent interaction.
-
(tool_cache¤ToolCache | None, default:None) –ToolCache with pre-resolved tool references from setup.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
-
digitalkin-
ArchetypeModule -
ToolModule -
TriggerHandler -
communityagno -
mixins-
AgUiMixinsend_message -
BaseMixin -
CostMixin -
FilesystemMixin -
LoggerMixin -
StorageMixin -
agui_mixinAgUiMixinsend_message -
base_mixinBaseMixin -
callback_mixinUserMessageMixinsend_message -
chat_history_mixinChatHistoryMixin -
cost_mixinCostMixin -
file_history_mixinFileHistoryMixin -
filesystem_mixinFilesystemMixin -
logger_mixinLoggerMixin -
storage_mixinStorageMixin
-
-
modules -
utilspackage_discoverModuleDiscovererinit_handlers
-
Methods:
-
cleanup–Close all service strategies and release their resources.
-
create_openai_style_tools–Create OpenAI-style function calling schemas for a tool module.
-
create_tool_functions–Create tool functions for all protocols in a tool setup.
-
get_module_schemas_by_id–Get module schemas by ID, discovering address/port from registry.
create_openai_style_tools
¤
Create OpenAI-style function calling schemas for a tool module.
Uses tool cache (fast path) with registry fallback. Returns one schema per ToolDefinition (protocol) in the module. Includes cost information both in the description and as separate metadata.
Parameters:
Returns:
create_tool_functions
¤
create_tool_functions(
slug: str,
) -> list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]
Create tool functions for all protocols in a tool setup.
Returns an async generator per ToolDefinition that calls the remote tool module via gRPC with the protocol auto-injected.
This method only uses the tool cache (no registry fallback). Use this in sync contexts like init methods.
Parameters:
Returns:
-
list[tuple[ToolDefinition, Callable[..., AsyncGenerator[dict, None]]]]–List of (ToolDefinition, async_generator_function) tuples. Empty if not found.
Session
¤
Session(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
timezone: tzinfo | None = None,
**kwargs: dict[str, Any],
)
flowchart TD
digitalkin.models.module.module_context.Session[Session]
click digitalkin.models.module.module_context.Session href "" "digitalkin.models.module.module_context.Session"
Session data container with mandatory setup_id and mission_id.
Raises:
-
ValueError–If mandatory args are missing.
Methods:
-
current_ids–Return current session ids as a dictionary.
module_types
¤
Types for module models - backward compatibility re-exports.
This module re-exports types from their new locations for backward compatibility. New code should import directly from the specific modules: - digitalkin.models.module.base_types for DataTrigger, DataModel, TypeVars - digitalkin.models.module.setup_types for SetupModel
Classes:
-
DataModel–Base definition of input/output model showing mandatory root fields.
-
DataTrigger–Defines the root input/output model exposing the protocol.
-
SetupModel–Base setup model with dynamic schema and tool cache support.
DataModel
¤
flowchart TD
digitalkin.models.module.module_types.DataModel[DataModel]
click digitalkin.models.module.module_types.DataModel href "" "digitalkin.models.module.module_types.DataModel"
Base definition of input/output model showing mandatory root fields.
The Model define the Module Input/output, usually referring to multiple input/output type defined by an union.
Example
class ModuleInput(DataModel): root: FileInput | MessageInput
-
digitalkin
DataTrigger
¤
flowchart TD
digitalkin.models.module.module_types.DataTrigger[DataTrigger]
click digitalkin.models.module.module_types.DataTrigger href "" "digitalkin.models.module.module_types.DataTrigger"
Defines the root input/output model exposing the protocol.
The mandatory protocol is important to define the module beahvior following the user or agent input/output.
Example
class MyInput(DataModel): root: DataTrigger user_define_data: Any
Usage¤
my_input = MyInput(root=DataTrigger(protocol="message")) print(my_input.root.protocol) # Output: message
SetupModel
¤
flowchart TD
digitalkin.models.module.module_types.SetupModel[SetupModel]
click digitalkin.models.module.module_types.SetupModel href "" "digitalkin.models.module.module_types.SetupModel"
Base setup model with dynamic schema and tool cache support.
Methods:
-
build_tool_cache–Build tool cache, resolving uncached tools via registry.
-
get_clean_model–Build filtered model based on json_schema_extra metadata.
build_tool_cache
async
¤
build_tool_cache(
registry: RegistryStrategy | None = None,
communication: CommunicationStrategy | None = None,
) -> ToolCache
Build tool cache, resolving uncached tools via registry.
Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.
Parameters:
-
(registry¤RegistryStrategy | None, default:None) –Registry service for resolving uncached tools.
-
(communication¤CommunicationStrategy | None, default:None) –Communication service for module schemas.
Returns:
-
ToolCache–ToolCache with resolved tool entries.
get_clean_model
async
classmethod
¤
get_clean_model(
*, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]
Build filtered model based on json_schema_extra metadata.
Parameters:
-
(config_fields¤bool) –Include fields with json_schema_extra["config"] = True.
-
(
bool) –Include fields with json_schema_extra["ui:widget"] = "hidden".
-
(force¤bool, default:False) –Refresh dynamic schema fields by calling providers.
Returns:
-
type[SetupModelT]–New BaseModel subclass with filtered fields.
request_metadata
¤
Immutable container for gRPC request metadata (headers).
Classes:
-
RequestMetadata–Immutable container for gRPC request metadata (headers).
RequestMetadata
¤
Immutable container for gRPC request metadata (headers).
Provides typed access to common auth headers and raw access to all metadata.
Filters out gRPC-reserved keys (prefixed with grpc-).
Example::
metadata = RequestMetadata({"authorization": "Bearer eyJ...", "x-tenant-id": "t-123"})
token = metadata.bearer_token # "eyJ..."
tenant = metadata.get("x-tenant-id") # "t-123"
Parameters:
-
(raw¤dict[str, str] | None, default:None) –Dictionary of metadata key-value pairs. Keys prefixed with
grpc-are filtered out.
Methods:
-
__bool__–Return True if metadata is non-empty.
-
__contains__–Check if a metadata key exists.
-
__getitem__–Get a metadata value by key.
-
__repr__–Return a string representation (sensitive values masked).
-
get–Get any metadata value by key.
-
to_dict–Return a copy of the raw metadata dictionary.
-
to_grpc_metadata–Convert to gRPC metadata format for forwarding.
Attributes:
-
api_key(str | None) –Get the
x-api-keyheader value. -
authorization(str | None) –Get the Authorization header value (e.g.,
Bearer <token>). -
bearer_token(str | None) –Extract the bearer token from the Authorization header.
authorization
property
¤
authorization: str | None
Get the Authorization header value (e.g., Bearer <token>).
bearer_token
property
¤
bearer_token: str | None
Extract the bearer token from the Authorization header.
Returns:
-
str | None–The token string if the Authorization header starts with
Bearer, otherwise None.
__contains__
¤
__getitem__
¤
get
¤
select_schema
¤
SelectSchema for trigger selection UI generation.
Classes:
-
SelectSchema–Base class for generating trigger selection schema.
SelectSchema
¤
flowchart TD
digitalkin.models.module.select_schema.SelectSchema[SelectSchema]
click digitalkin.models.module.select_schema.SelectSchema href "" "digitalkin.models.module.select_schema.SelectSchema"
Base class for generating trigger selection schema.
Subclass and add boolean fields to customize the selection UI.
If no fields are defined, schema is auto-generated from registered protocols.
Set select_format = None in your module to disable.
Example
class MySelectSchema(SelectSchema): message: bool = Field(default=True, title="Message", description="Process messages") file: bool = Field(default=False, title="File", description="Process files")
Methods:
-
build–Build the select schema.
build
classmethod
¤
Build the select schema.
If the subclass has user-defined fields, uses those. Otherwise, auto-generates from protocols_info.
Parameters:
Returns:
setup_types
¤
Setup model types with dynamic schema resolution and tool reference support.
Classes:
-
SetupModel–Base setup model with dynamic schema and tool cache support.
SetupModel
¤
flowchart TD
digitalkin.models.module.setup_types.SetupModel[SetupModel]
click digitalkin.models.module.setup_types.SetupModel href "" "digitalkin.models.module.setup_types.SetupModel"
Base setup model with dynamic schema and tool cache support.
Methods:
-
build_tool_cache–Build tool cache, resolving uncached tools via registry.
-
get_clean_model–Build filtered model based on json_schema_extra metadata.
build_tool_cache
async
¤
build_tool_cache(
registry: RegistryStrategy | None = None,
communication: CommunicationStrategy | None = None,
) -> ToolCache
Build tool cache, resolving uncached tools via registry.
Walks ToolReference fields recursively. For each selected tool, checks resolved_tools first (cache). If missing and registry is available, resolves via gRPC and populates the cache.
Parameters:
-
(registry¤RegistryStrategy | None, default:None) –Registry service for resolving uncached tools.
-
(communication¤CommunicationStrategy | None, default:None) –Communication service for module schemas.
Returns:
-
ToolCache–ToolCache with resolved tool entries.
get_clean_model
async
classmethod
¤
get_clean_model(
*, config_fields: bool, hidden_fields: bool, force: bool = False
) -> type[SetupModelT]
Build filtered model based on json_schema_extra metadata.
Parameters:
-
(config_fields¤bool) –Include fields with json_schema_extra["config"] = True.
-
(
bool) –Include fields with json_schema_extra["ui:widget"] = "hidden".
-
(force¤bool, default:False) –Refresh dynamic schema fields by calling providers.
Returns:
-
type[SetupModelT]–New BaseModel subclass with filtered fields.
tool_cache
¤
Tool cache for resolved tool references.
Classes:
-
SelectedTool–Selected tool information.
-
ToolCache–Registry cache storing resolved tool references by setup field name.
-
ToolDefinition–Complete definition of an LLM tool with resolved JSON Schema parameters.
-
ToolModuleInfo–Module info for tool modules.
Functions:
-
module_info_to_tool_module_info–Convert ModuleInfo to ToolModuleInfo by fetching schemas via gRPC.
SelectedTool
¤
flowchart TD
digitalkin.models.module.tool_cache.SelectedTool[SelectedTool]
click digitalkin.models.module.tool_cache.SelectedTool href "" "digitalkin.models.module.tool_cache.SelectedTool"
Selected tool information.
ToolCache
¤
flowchart TD
digitalkin.models.module.tool_cache.ToolCache[ToolCache]
click digitalkin.models.module.tool_cache.ToolCache href "" "digitalkin.models.module.tool_cache.ToolCache"
Registry cache storing resolved tool references by setup field name.
Methods:
-
add–Add a tool to the cache.
-
clear–Clear all cache entries.
-
get–Get a tool from cache, optionally querying registry on miss.
-
list_tools–List all cached tool names.
add
¤
add(tool_module_info: ToolModuleInfo) -> None
Add a tool to the cache.
Parameters:
-
(tool_module_info¤ToolModuleInfo) –Resolved tool module information.
get
¤
get(setup_id: str) -> ToolModuleInfo | None
Get a tool from cache, optionally querying registry on miss.
Parameters:
Returns:
-
ToolModuleInfo | None–ToolModuleInfo if found, None otherwise.
ToolDefinition
¤
flowchart TD
digitalkin.models.module.tool_cache.ToolDefinition[ToolDefinition]
click digitalkin.models.module.tool_cache.ToolDefinition href "" "digitalkin.models.module.tool_cache.ToolDefinition"
Complete definition of an LLM tool with resolved JSON Schema parameters.
Attributes:
-
name(str) –Tool name (from protocol const or trigger class name).
-
description(str) –Tool description (from trigger docstring).
-
parameters_schema(dict[str, Any]) –JSON Schema object describing the tool's parameters.
ToolModuleInfo
¤
flowchart TD
digitalkin.models.module.tool_cache.ToolModuleInfo[ToolModuleInfo]
digitalkin.models.services.registry.ModuleInfo[ModuleInfo]
digitalkin.models.services.registry.ModuleInfo --> digitalkin.models.module.tool_cache.ToolModuleInfo
click digitalkin.models.module.tool_cache.ToolModuleInfo href "" "digitalkin.models.module.tool_cache.ToolModuleInfo"
click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
Module info for tool modules.
Attributes:
module_info_to_tool_module_info
async
¤
module_info_to_tool_module_info(
module_info: ModuleInfo,
setup_id: str,
tool_name: str,
communication: CommunicationStrategy,
*,
llm_format: bool = True,
) -> ToolModuleInfo
Convert ModuleInfo to ToolModuleInfo by fetching schemas via gRPC.
Fetches the module's input schema and extracts tool definitions from the discriminated union structure.
Parameters:
-
(module_info¤ModuleInfo) –Module info from registry.
-
(setup_id¤str) –Setup ID of the selected tool.
-
(tool_name¤str) –Name of the tool.
-
(communication¤CommunicationStrategy) –Communication strategy for gRPC calls.
-
(llm_format¤bool, default:True) –Use LLM-friendly schema format.
Returns:
-
ToolModuleInfo–ToolModuleInfo with tools extracted from input schema.
tool_reference
¤
Tool reference types for module configuration.
Classes:
-
ToolReference–Tool selection containing setup IDs and trigger filters.
-
ToolSelection–Single tool selection with trigger filtering.
Functions:
-
tool_reference_input–Create ToolReferenceInput type with schema options and validation.
ToolReference
¤
flowchart TD
digitalkin.models.module.tool_reference.ToolReference[ToolReference]
click digitalkin.models.module.tool_reference.ToolReference href "" "digitalkin.models.module.tool_reference.ToolReference"
Tool selection containing setup IDs and trigger filters.
Methods:
-
resolve–Resolve selected tools using the registry.
resolve
async
¤
resolve(
registry: RegistryStrategy, communication: CommunicationStrategy
) -> list[ToolModuleInfo]
Resolve selected tools using the registry.
Each tool resolution is bounded by DIGITALKIN_TOOL_RESOLVE_TIMEOUT (default 10s).
Parameters:
-
(registry¤RegistryStrategy) –Registry service for module discovery.
-
(communication¤CommunicationStrategy) –Communication service for module schemas.
Returns:
-
list[ToolModuleInfo]–List of ToolModuleInfo for resolved tools, filtered by enabled triggers.
ToolSelection
¤
flowchart TD
digitalkin.models.module.tool_reference.ToolSelection[ToolSelection]
click digitalkin.models.module.tool_reference.ToolSelection href "" "digitalkin.models.module.tool_reference.ToolSelection"
Single tool selection with trigger filtering.
tool_reference_input
¤
tool_reference_input(
setup_ids: list[str] | None = None,
module_ids: list[str] | None = None,
tag_ids: list[str] | None = None,
categories: list[str] | None = None,
max_tools: int = 0,
min_tools: int = 0,
) -> type[ToolReference]
Create ToolReferenceInput type with schema options and validation.
Parameters:
-
(setup_ids¤list[str] | None, default:None) –Setup IDs for the user to choose from.
-
(module_ids¤list[str] | None, default:None) –Module IDs for the user to choose from.
-
(tag_ids¤list[str] | None, default:None) –Tag IDs for the user to choose from.
-
(categories¤list[str] | None, default:None) –Categories for the user to choose from.
-
(max_tools¤int, default:0) –Maximum tools allowed. 0 for unlimited.
-
(min_tools¤int, default:0) –Minimum tools required. 0 for no minimum.
Returns:
-
type[ToolReference]–Annotated type for use in Pydantic models.
utility
¤
Utility protocols for SDK-provided functionality.
These protocols are automatically available to all modules and don't need to be explicitly included in module output unions.
Classes:
-
EndOfStreamOutput–Signal that the stream has ended.
-
HealthcheckPingInput–Input for healthcheck ping request.
-
HealthcheckPingOutput–Output for healthcheck ping response.
-
HealthcheckServicesInput–Input for healthcheck services request.
-
HealthcheckServicesOutput–Output for healthcheck services response.
-
HealthcheckStatusInput–Input for healthcheck status request.
-
HealthcheckStatusOutput–Output for healthcheck status response.
-
ModuleStartInfoOutput–Output sent when module starts with execution context.
-
ServiceHealthStatus–Health status of a single service.
-
UtilityProtocol–Base class for SDK-provided utility protocols.
-
UtilityRegistry–Registry for SDK-provided built-in triggers.
EndOfStreamOutput
¤
flowchart TD
digitalkin.models.module.utility.EndOfStreamOutput[EndOfStreamOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.EndOfStreamOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.EndOfStreamOutput href "" "digitalkin.models.module.utility.EndOfStreamOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Signal that the stream has ended.
HealthcheckPingInput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckPingInput[HealthcheckPingInput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckPingInput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckPingInput href "" "digitalkin.models.module.utility.HealthcheckPingInput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Input for healthcheck ping request.
HealthcheckPingOutput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckPingOutput[HealthcheckPingOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckPingOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckPingOutput href "" "digitalkin.models.module.utility.HealthcheckPingOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Output for healthcheck ping response.
Simple alive check that returns "pong" status.
HealthcheckServicesInput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckServicesInput[HealthcheckServicesInput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckServicesInput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckServicesInput href "" "digitalkin.models.module.utility.HealthcheckServicesInput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Input for healthcheck services request.
HealthcheckServicesOutput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckServicesOutput[HealthcheckServicesOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckServicesOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckServicesOutput href "" "digitalkin.models.module.utility.HealthcheckServicesOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Output for healthcheck services response.
Reports the health status of all configured services.
HealthcheckStatusInput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckStatusInput[HealthcheckStatusInput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckStatusInput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckStatusInput href "" "digitalkin.models.module.utility.HealthcheckStatusInput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Input for healthcheck status request.
HealthcheckStatusOutput
¤
flowchart TD
digitalkin.models.module.utility.HealthcheckStatusOutput[HealthcheckStatusOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.HealthcheckStatusOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.HealthcheckStatusOutput href "" "digitalkin.models.module.utility.HealthcheckStatusOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Output for healthcheck status response.
Comprehensive module status including uptime, active jobs, and metadata.
ModuleStartInfoOutput
¤
flowchart TD
digitalkin.models.module.utility.ModuleStartInfoOutput[ModuleStartInfoOutput]
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.utility.UtilityProtocol --> digitalkin.models.module.utility.ModuleStartInfoOutput
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.ModuleStartInfoOutput href "" "digitalkin.models.module.utility.ModuleStartInfoOutput"
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Output sent when module starts with execution context.
This protocol is sent as the first message when a module starts, providing the client with essential execution context information.
ServiceHealthStatus
¤
flowchart TD
digitalkin.models.module.utility.ServiceHealthStatus[ServiceHealthStatus]
click digitalkin.models.module.utility.ServiceHealthStatus href "" "digitalkin.models.module.utility.ServiceHealthStatus"
Health status of a single service.
UtilityProtocol
¤
flowchart TD
digitalkin.models.module.utility.UtilityProtocol[UtilityProtocol]
digitalkin.models.module.base_types.DataTrigger[DataTrigger]
digitalkin.models.module.base_types.DataTrigger --> digitalkin.models.module.utility.UtilityProtocol
click digitalkin.models.module.utility.UtilityProtocol href "" "digitalkin.models.module.utility.UtilityProtocol"
click digitalkin.models.module.base_types.DataTrigger href "" "digitalkin.models.module.base_types.DataTrigger"
Base class for SDK-provided utility protocols.
All SDK utility protocols inherit from this class to enable: - Easy identification of SDK vs user-defined protocols - Auto-injection capability - Consistent behavior across the SDK
UtilityRegistry
¤
Registry for SDK-provided built-in triggers.
Example
builtin_triggers = UtilityRegistry.get_builtin_triggers()
Methods:
-
get_builtin_triggers–Get all SDK-provided built-in trigger handlers.
services
¤
This module contains the models for the services.
Modules:
Classes:
-
BaseMessage–Base Model representing a simple message in the chat history.
-
BaseRole–Officially supported Role Enum for chat messages.
-
ChatHistory–Storage chat history model for the OpenAI Archetype module.
BaseMessage
¤
flowchart TD
digitalkin.models.services.BaseMessage[BaseMessage]
click digitalkin.models.services.BaseMessage href "" "digitalkin.models.services.BaseMessage"
Base Model representing a simple message in the chat history.
BaseRole
¤
flowchart TD
digitalkin.models.services.BaseRole[BaseRole]
click digitalkin.models.services.BaseRole href "" "digitalkin.models.services.BaseRole"
Officially supported Role Enum for chat messages.
ChatHistory
¤
flowchart TD
digitalkin.models.services.ChatHistory[ChatHistory]
click digitalkin.models.services.ChatHistory href "" "digitalkin.models.services.ChatHistory"
Storage chat history model for the OpenAI Archetype module.
cost
¤
Pydantic models for cost service.
Classes:
-
AmountLimit–Cost limit based on cost amount in dollars (e.g., max $1.00).
-
CostConfig–Pydantic model that defines a cost configuration.
-
CostEvent–Pydantic model that represents a cost event registered during service execution.
-
CostTypeEnum–Enumeration of supported cost types.
-
QuantityLimit–Cost limit based on quantity (e.g., max 10000 tokens).
AmountLimit
¤
flowchart TD
digitalkin.models.services.cost.AmountLimit[AmountLimit]
click digitalkin.models.services.cost.AmountLimit href "" "digitalkin.models.services.cost.AmountLimit"
Cost limit based on cost amount in dollars (e.g., max $1.00).
CostConfig
¤
flowchart TD
digitalkin.models.services.cost.CostConfig[CostConfig]
click digitalkin.models.services.cost.CostConfig href "" "digitalkin.models.services.cost.CostConfig"
Pydantic model that defines a cost configuration.
:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).
CostEvent
¤
flowchart TD
digitalkin.models.services.cost.CostEvent[CostEvent]
click digitalkin.models.services.cost.CostEvent href "" "digitalkin.models.services.cost.CostEvent"
Pydantic model that represents a cost event registered during service execution.
DEPRECATED¤
:param cost_name: Identifier for the cost configuration. :param cost_type: The type of cost. :param usage: The amount or units consumed. :param cost_amount: The computed cost amount; if not provided it is computed as usage*rate. :param timestamp: The time when the cost event was recorded. :param metadata: Additional contextual information about the cost event.
CostTypeEnum
¤
flowchart TD
digitalkin.models.services.cost.CostTypeEnum[CostTypeEnum]
click digitalkin.models.services.cost.CostTypeEnum href "" "digitalkin.models.services.cost.CostTypeEnum"
Enumeration of supported cost types.
QuantityLimit
¤
flowchart TD
digitalkin.models.services.cost.QuantityLimit[QuantityLimit]
click digitalkin.models.services.cost.QuantityLimit href "" "digitalkin.models.services.cost.QuantityLimit"
Cost limit based on quantity (e.g., max 10000 tokens).
registry
¤
Registry data models.
Classes:
-
ModuleInfo–Module information from registry.
-
RegistryModuleStatus–Module status in the registry.
-
RegistryModuleType–Module type in the registry.
-
RegistrySetupStatus–Setup status in the registry.
-
RegistryVisibility–Visibility in the registry.
-
SetupInfo–Setup information from registry.
ModuleInfo
¤
flowchart TD
digitalkin.models.services.registry.ModuleInfo[ModuleInfo]
click digitalkin.models.services.registry.ModuleInfo href "" "digitalkin.models.services.registry.ModuleInfo"
Module information from registry.
RegistryModuleStatus
¤
flowchart TD
digitalkin.models.services.registry.RegistryModuleStatus[RegistryModuleStatus]
click digitalkin.models.services.registry.RegistryModuleStatus href "" "digitalkin.models.services.registry.RegistryModuleStatus"
Module status in the registry.
RegistryModuleType
¤
flowchart TD
digitalkin.models.services.registry.RegistryModuleType[RegistryModuleType]
click digitalkin.models.services.registry.RegistryModuleType href "" "digitalkin.models.services.registry.RegistryModuleType"
Module type in the registry.
RegistrySetupStatus
¤
flowchart TD
digitalkin.models.services.registry.RegistrySetupStatus[RegistrySetupStatus]
click digitalkin.models.services.registry.RegistrySetupStatus href "" "digitalkin.models.services.registry.RegistrySetupStatus"
Setup status in the registry.
RegistryVisibility
¤
flowchart TD
digitalkin.models.services.registry.RegistryVisibility[RegistryVisibility]
click digitalkin.models.services.registry.RegistryVisibility href "" "digitalkin.models.services.registry.RegistryVisibility"
Visibility in the registry.
SetupInfo
¤
flowchart TD
digitalkin.models.services.registry.SetupInfo[SetupInfo]
click digitalkin.models.services.registry.SetupInfo href "" "digitalkin.models.services.registry.SetupInfo"
Setup information from registry.
storage
¤
Storage model.
Classes:
-
BaseMessage–Base Model representing a simple message in the chat history.
-
BaseRole–Officially supported Role Enum for chat messages.
-
ChatHistory–Storage chat history model for the OpenAI Archetype module.
-
FileHistory–File history model.
-
FileModel–File model.
BaseMessage
¤
flowchart TD
digitalkin.models.services.storage.BaseMessage[BaseMessage]
click digitalkin.models.services.storage.BaseMessage href "" "digitalkin.models.services.storage.BaseMessage"
Base Model representing a simple message in the chat history.
BaseRole
¤
flowchart TD
digitalkin.models.services.storage.BaseRole[BaseRole]
click digitalkin.models.services.storage.BaseRole href "" "digitalkin.models.services.storage.BaseRole"
Officially supported Role Enum for chat messages.
ChatHistory
¤
flowchart TD
digitalkin.models.services.storage.ChatHistory[ChatHistory]
click digitalkin.models.services.storage.ChatHistory href "" "digitalkin.models.services.storage.ChatHistory"
Storage chat history model for the OpenAI Archetype module.
FileHistory
¤
flowchart TD
digitalkin.models.services.storage.FileHistory[FileHistory]
click digitalkin.models.services.storage.FileHistory href "" "digitalkin.models.services.storage.FileHistory"
File history model.
FileModel
¤
flowchart TD
digitalkin.models.services.storage.FileModel[FileModel]
click digitalkin.models.services.storage.FileModel href "" "digitalkin.models.services.storage.FileModel"
File model.
settings
¤
This package contain settings of sdk.
Modules:
server
¤
Package for server settings.
Modules:
-
channel–Server channel settings.
-
grpc–gRPC server settings for the SDK.
-
server–Server settings for the DigitalKin application.
channel
¤
Server channel settings.
Classes:
-
ServerChannelSettings–Settings for a server channel.
ServerChannelSettings
¤
ServerChannelSettings(**values: Any)
flowchart TD
digitalkin.models.settings.server.channel.ServerChannelSettings[ServerChannelSettings]
digitalkin.models.settings.utils.channel.BaseChannelSettings[BaseChannelSettings]
digitalkin.models.settings.utils.channel.BaseChannelSettings --> digitalkin.models.settings.server.channel.ServerChannelSettings
click digitalkin.models.settings.server.channel.ServerChannelSettings href "" "digitalkin.models.settings.server.channel.ServerChannelSettings"
click digitalkin.models.settings.utils.channel.BaseChannelSettings href "" "digitalkin.models.settings.utils.channel.BaseChannelSettings"
Settings for a server channel.
Attributes:
-
advertise_host(str | None) –Public hostname/IP sent to registry for discovery. Falls back to host if not set.
-
database_url(str | None) –Database URL for registry data storage
Methods:
-
validate_credentials–Validate that credentials are provided when in secure mode.
-
validate_port–Validate that the port is in a valid range.
validate_credentials
¤validate_credentials() -> BaseChannelSettings
Validate that credentials are provided when in secure mode.
Returns:
-
BaseChannelSettings–The validated credentials
Raises:
-
ConfigurationError–If credentials are missing in secure mode
grpc
¤
gRPC server settings for the SDK.
Classes:
-
GrpcServerSettings–gRPC tuning settings on the SDK side.
GrpcServerSettings
¤
GrpcServerSettings(**values: Any)
flowchart TD
digitalkin.models.settings.server.grpc.GrpcServerSettings[GrpcServerSettings]
click digitalkin.models.settings.server.grpc.GrpcServerSettings href "" "digitalkin.models.settings.server.grpc.GrpcServerSettings"
gRPC tuning settings on the SDK side.
Attributes:
-
compression(GrpcCompression) –gRPC compression algorithm to use for server responses.
-
keepalive_time(NonNegativeFloat) –Interval for server keepalive pings, in milliseconds.
-
keepalive_timeout(NonNegativeFloat) –Timeout for server keepalive pings, in milliseconds.
-
min_ping_interval(NonNegativeFloat) –Minimum interval between HTTP/2 pings on the server side, in milliseconds.
-
max_receive_message_lenght(NonNegativeFloat) –Maximum message size the server can receive, in bytes.
-
max_send_message_length(NonNegativeFloat) –Maximum message size the server can send, in bytes.
-
max_pings_without_data(NonNegativeFloat) –Maximum number of pings the server allows without receiving any data.
-
keepalive_permit_without_calls(bool) –Allow clients to send keepalive pings even when there are no active RPCs.
server
¤
Server settings for the DigitalKin application.
Classes:
-
ServerSettings–Settings for the DigitalKin server.
ServerSettings
¤
ServerSettings(**values: Any)
flowchart TD
digitalkin.models.settings.server.server.ServerSettings[ServerSettings]
click digitalkin.models.settings.server.server.ServerSettings href "" "digitalkin.models.settings.server.server.ServerSettings"
Settings for the DigitalKin server.
Attributes:
-
channel(ServerChannelSettings) –Settings for the server channel.
-
grpc(GrpcServerSettings) –Settings for the gRPC server.
-
health_check(bool) –Whether to enable the health check service.
-
reflection(bool) –Whether to enable reflection for the server.
-
max_concurrent_rpcs(NonNegativeInt) –Maximum number of RPCs handled in parallel by the server.
-
max_workers(NonNegativeInt) –Maximum number of workers for sync mode.
-
thread_pool_workers(NonNegativeInt) –Number of workers in the server thread pool.
utils
¤
This package contain channel base.
Modules:
-
channel–This file define channelBase for grpc config.
channel
¤
This file define channelBase for grpc config.
Classes:
-
BaseChannelSettings–Base settings model for gRPC channel configuration.
-
ControlFlow–Enum for server operation mode.
-
Credentials–Model for server credentials in secure mode.
-
SecurityMode–Enum for server security mode.
BaseChannelSettings
¤
BaseChannelSettings(**values: Any)
flowchart TD
digitalkin.models.settings.utils.channel.BaseChannelSettings[BaseChannelSettings]
click digitalkin.models.settings.utils.channel.BaseChannelSettings href "" "digitalkin.models.settings.utils.channel.BaseChannelSettings"
Base settings model for gRPC channel configuration.
Methods:
-
validate_credentials–Validate that credentials are provided when in secure mode.
-
validate_port–Validate that the port is in a valid range.
Attributes:
validate_credentials
¤validate_credentials() -> BaseChannelSettings
Validate that credentials are provided when in secure mode.
Returns:
-
BaseChannelSettings–The validated credentials
Raises:
-
ConfigurationError–If credentials are missing in secure mode
ControlFlow
¤
flowchart TD
digitalkin.models.settings.utils.channel.ControlFlow[ControlFlow]
click digitalkin.models.settings.utils.channel.ControlFlow href "" "digitalkin.models.settings.utils.channel.ControlFlow"
Enum for server operation mode.
Credentials
¤
Credentials(**data: Any)
flowchart TD
digitalkin.models.settings.utils.channel.Credentials[Credentials]
click digitalkin.models.settings.utils.channel.Credentials href "" "digitalkin.models.settings.utils.channel.Credentials"
Model for server credentials in secure mode.
Attributes:
-
key_path(Path | None) –Path to the server private key
-
cert_path(Path | None) –Path to the server certificate
-
root_cert_path(Path | None) –Optional path to the root certificate
Methods:
-
check_path_exists–Validate that the file path exists.
SecurityMode
¤
flowchart TD
digitalkin.models.settings.utils.channel.SecurityMode[SecurityMode]
click digitalkin.models.settings.utils.channel.SecurityMode href "" "digitalkin.models.settings.utils.channel.SecurityMode"
Enum for server security mode.
modules
¤
Module package for DigitalKin.
Modules:
-
archetype_module–ArchetypeModule extends BaseModule to implement specific module types.
-
tool_module–ToolModule extends BaseModule to implement specific module types.
-
trigger_handler–Definition of the Trigger type.
-
triggers–Built-in SDK triggers.
Classes:
-
ArchetypeModule–ArchetypeModule extends BaseModule to implement specific module types.
-
ToolModule–ToolModule extends BaseModule to implement specific module types.
-
TriggerHandler–Base class for all input-trigger handlers.
ArchetypeModule
¤
ArchetypeModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.modules.ArchetypeModule[ArchetypeModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.modules.ArchetypeModule
click digitalkin.modules.ArchetypeModule href "" "digitalkin.modules.ArchetypeModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ArchetypeModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
ToolModule
¤
ToolModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.modules.ToolModule[ToolModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.modules.ToolModule
click digitalkin.modules.ToolModule href "" "digitalkin.modules.ToolModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ToolModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
TriggerHandler
¤
TriggerHandler(context: ModuleContext)
flowchart TD
digitalkin.modules.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.modules.TriggerHandler href "" "digitalkin.modules.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Base class for all input-trigger handlers.
Each handler declares
- protocol_key: the Literal value this handler processes
- handle(): logic to process the validated payload
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Asynchronously processes the input data specific to Handler and streams results via the provided callback.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
abstractmethod
async
¤
handle(
input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None
Asynchronously processes the input data specific to Handler and streams results via the provided callback.
Parameters:
-
(input_data¤InputModelT) –The input data to be processed by the handler.
-
(setup_data¤SetupModelT) –The setup or configuration data required for processing.
-
(context¤ModuleContext) –The context object containing module-specific information and resources.
Returns:
-
Any(None) –The result of the processing, if applicable.
Note
self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])
The callback must be awaited to ensure results are streamed correctly during processing.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
archetype_module
¤
ArchetypeModule extends BaseModule to implement specific module types.
Classes:
-
ArchetypeModule–ArchetypeModule extends BaseModule to implement specific module types.
ArchetypeModule
¤
ArchetypeModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.modules.archetype_module.ArchetypeModule[ArchetypeModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.modules.archetype_module.ArchetypeModule
click digitalkin.modules.archetype_module.ArchetypeModule href "" "digitalkin.modules.archetype_module.ArchetypeModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ArchetypeModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
tool_module
¤
ToolModule extends BaseModule to implement specific module types.
Classes:
-
ToolModule–ToolModule extends BaseModule to implement specific module types.
ToolModule
¤
ToolModule(
job_id: str,
mission_id: str,
setup_id: str,
setup_version_id: str,
request_metadata: dict[str, str] | None = None,
)
flowchart TD
digitalkin.modules.tool_module.ToolModule[ToolModule]
digitalkin.modules._base_module.BaseModule[BaseModule]
digitalkin.modules._base_module.BaseModule --> digitalkin.modules.tool_module.ToolModule
click digitalkin.modules.tool_module.ToolModule href "" "digitalkin.modules.tool_module.ToolModule"
click digitalkin.modules._base_module.BaseModule href "" "digitalkin.modules._base_module.BaseModule"
ToolModule extends BaseModule to implement specific module types.
Parameters:
-
(job_id¤str) –Unique job identifier.
-
(mission_id¤str) –Mission identifier.
-
(setup_id¤str) –Setup identifier.
-
(setup_version_id¤str) –Setup version identifier.
-
(request_metadata¤dict[str, str] | None, default:None) –gRPC request metadata (headers) from the incoming request.
Methods:
-
__init_subclass__–Ensure each subclass has its own copy of mutable class variables.
-
cleanup–Run the module.
-
create_config_setup_model–Create the setup model from the setup data.
-
create_input_model–Create the input model from the input data.
-
create_output_model–Create the output model from the output data.
-
create_secret_model–Create the secret model from the secret data.
-
create_setup_model–Create the setup model from the setup data.
-
discover–Discover and register all TriggerHandler subclasses in the specified package or current directory.
-
get_config_setup_format–Gets the JSON schema of the config setup format model.
-
get_cost_format–Get the JSON schema of the cost configuration.
-
get_input_format–Get the JSON schema of the input format model.
-
get_module_id–Get the module ID from environment variable or metadata.
-
get_output_format–Get the JSON schema of the output format model.
-
get_secret_format–Get the JSON schema of the secret format model.
-
get_select_input_format–Get the JSON schema for trigger selection UI.
-
get_setup_format–Gets the JSON schema of the setup format model.
-
initialize–Initialize the module.
-
register–Dynamically register the trigger class.
-
run–Run the module by dispatching to the appropriate trigger handler.
-
run_config_setup–Run config setup the module.
-
start–Start the module.
-
start_config_setup–Run config setup lifecycle with tool resolution in parallel.
-
stop–Stop the module. Idempotent — second call is a no-op.
Attributes:
-
status(ModuleStatus) –Get the module status.
status
property
¤
status: ModuleStatus
__init_subclass__
¤
__init_subclass__(**kwargs: Any) -> None
Ensure each subclass has its own copy of mutable class variables.
create_config_setup_model
classmethod
¤
create_config_setup_model(config_setup_data: dict[str, Any]) -> SetupModelT
create_output_model
classmethod
¤
create_output_model(output_data: dict[str, Any]) -> OutputModelT
create_secret_model
classmethod
¤
create_secret_model(secret_data: dict[str, Any]) -> SecretModelT
create_setup_model
async
classmethod
¤
create_setup_model(
setup_data: dict[str, Any], *, config_fields: bool = False
) -> SetupModelT
Create the setup model from the setup data.
Creates a filtered setup model instance based on the provided data.
Uses get_clean_model() internally to get the appropriate model class
with field filtering applied.
Parameters:
-
(setup_data¤dict[str, Any]) –The setup data to create the model from.
-
(config_fields¤bool, default:False) –If True, include only fields with json_schema_extra["config"] == True.
Returns:
-
SetupModelT–An instance of the setup model with the provided data.
discover
classmethod
¤
discover() -> None
Discover and register all TriggerHandler subclasses in the specified package or current directory.
Dynamically import all Python modules in the specified package or current directory, triggering class registrations for subclasses of TriggerHandler whose names end with 'Trigger'.
If a package is provided, all .py files within its path are imported; otherwise, the current working directory is searched. For each imported module, any class matching the criteria is registered via cls.register(). Errors during import are logged at debug level.
Built-in healthcheck handlers (ping, services, status) are automatically registered to provide standard healthcheck functionality for all modules.
get_config_setup_format
async
classmethod
¤
get_config_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the config setup format model.
The config setup format is used only to initialize the module with configuration
data. It includes fields marked with json_schema_extra={"config": True} and
excludes hidden runtime fields.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the config setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
get_cost_format
async
classmethod
¤
get_cost_format(*, llm_format: bool) -> str
Get the JSON schema of the cost configuration.
Extracts CostConfig from services_config_params["cost"]["config"]
and returns as JSON schema.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the cost configuration as a JSON string.
get_input_format
async
classmethod
¤
get_input_format(*, llm_format: bool) -> str
Get the JSON schema of the input format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the input format as a JSON string.
Raises:
-
NotImplementedError–If the
input_formatclass attribute is not defined.
get_output_format
async
classmethod
¤
get_output_format(*, llm_format: bool) -> str
Get the JSON schema of the output format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the output format as a JSON string.
Raises:
-
NotImplementedError–If the
output_formatclass attribute is not defined.
get_secret_format
async
classmethod
¤
get_secret_format(*, llm_format: bool) -> str
Get the JSON schema of the secret format model.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the secret format as a JSON string.
Raises:
-
NotImplementedError–If the
secret_formatclass attribute is not defined.
get_setup_format
async
classmethod
¤
get_setup_format(*, llm_format: bool) -> str
Gets the JSON schema of the setup format model.
The setup format is used at runtime and includes hidden fields but excludes config-only fields. This is the schema used when running the module.
Dynamic schema fields are always resolved when generating the schema, as this method is typically called during module discovery or schema generation where fresh values are needed.
Parameters:
-
(llm_format¤bool) –If True, return LLM-optimized schema format with inlined references and simplified structure.
Returns:
-
str–The JSON schema of the setup format as a JSON string.
Raises:
-
NotImplementedError–If the
setup_formatclass attribute is not defined.
initialize
abstractmethod
async
¤
initialize(context: ModuleContext, setup_data: SetupModelT) -> None
Initialize the module.
register
classmethod
¤
register(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Dynamically register the trigger class.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –type of the trigger handler to register.
Returns:
-
type[TriggerHandler]–type of the trigger handler.
run
async
¤
run(input_data: InputModelT, setup_data: SetupModelT) -> None
Run the module by dispatching to the appropriate trigger handler.
Parameters:
-
(input_data¤InputModelT) –Input data to process.
-
(setup_data¤SetupModelT) –Configuration data for the module.
Raises:
-
ValueError–If no handler for the protocol is found.
run_config_setup
async
¤
run_config_setup(context: ModuleContext, config_setup_data: SetupModelT) -> SetupModelT
Run config setup the module.
The config setup is used to initialize the setup with configuration data. This method is typically used to set up the module with necessary configuration before running it, especially for processing data like files. The function needs to save the setup in the storage. The module will be initialize with the setup and not the config setup. This method is optional, the config setup and setup can be the same.
Returns:
-
SetupModelT–The updated setup model after running the config setup.
start
async
¤
start(
input_data: InputModelT,
setup_data: SetupModelT,
callback: Callable[
[OutputModelT | ModuleCodeModel | DataModel[UtilityProtocol]],
Coroutine[Any, Any, None],
],
done_callback: Callable | None = None,
) -> None
Start the module.
start_config_setup
async
¤
start_config_setup(
config_setup_data: SetupModelT,
callback: Callable[[SetupModelT | ModuleCodeModel], Coroutine[Any, Any, None]],
) -> None
trigger_handler
¤
Definition of the Trigger type.
Classes:
-
TriggerHandler–Base class for all input-trigger handlers.
TriggerHandler
¤
TriggerHandler(context: ModuleContext)
flowchart TD
digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Base class for all input-trigger handlers.
Each handler declares
- protocol_key: the Literal value this handler processes
- handle(): logic to process the validated payload
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Asynchronously processes the input data specific to Handler and streams results via the provided callback.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
abstractmethod
async
¤
handle(
input_data: InputModelT, setup_data: SetupModelT, context: ModuleContext
) -> None
Asynchronously processes the input data specific to Handler and streams results via the provided callback.
Parameters:
-
(input_data¤InputModelT) –The input data to be processed by the handler.
-
(setup_data¤SetupModelT) –The setup or configuration data required for processing.
-
(context¤ModuleContext) –The context object containing module-specific information and resources.
Returns:
-
Any(None) –The result of the processing, if applicable.
Note
self.send_message: callback used to stream results. (Callable[[OutputModelT], Coroutine[Any, Any, None]])
The callback must be awaited to ensure results are streamed correctly during processing.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
triggers
¤
Built-in SDK triggers.
These triggers are automatically registered without requiring discovery. They provide standard functionality available to all modules.
Note: These are internal triggers. External code should not import them directly. Use UtilityRegistry.get_builtin_triggers() to access the trigger classes.
Modules:
-
healthcheck_ping_trigger–Healthcheck ping trigger - simple alive check.
-
healthcheck_services_trigger–Healthcheck services trigger - reports service health.
-
healthcheck_status_trigger–Healthcheck status trigger - comprehensive module status.
healthcheck_ping_trigger
¤
Healthcheck ping trigger - simple alive check.
Classes:
-
HealthcheckPingTrigger–Handler for simple ping healthcheck.
HealthcheckPingTrigger
¤
HealthcheckPingTrigger(context: ModuleContext)
flowchart TD
digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger[HealthcheckPingTrigger]
digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger href "" "digitalkin.modules.triggers.healthcheck_ping_trigger.HealthcheckPingTrigger"
click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Handler for simple ping healthcheck.
Responds immediately with "pong" status to verify the module is responsive.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Handle ping healthcheck request.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
async
¤
handle(
input_data: HealthcheckPingInput, setup_data: Any, context: ModuleContext
) -> None
Handle ping healthcheck request.
Parameters:
-
(input_data¤HealthcheckPingInput) –The input trigger data (unused for healthcheck).
-
(setup_data¤Any) –The setup configuration (unused for healthcheck).
-
(context¤ModuleContext) –The module context.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
healthcheck_services_trigger
¤
Healthcheck services trigger - reports service health.
Classes:
-
HealthcheckServicesTrigger–Handler for services healthcheck.
HealthcheckServicesTrigger
¤
HealthcheckServicesTrigger(context: ModuleContext)
flowchart TD
digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger[HealthcheckServicesTrigger]
digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger href "" "digitalkin.modules.triggers.healthcheck_services_trigger.HealthcheckServicesTrigger"
click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Handler for services healthcheck.
Reports the health status of all configured services (storage, cost, filesystem, etc.).
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Handle services healthcheck request.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
async
¤
handle(
input_data: HealthcheckServicesInput, setup_data: Any, context: ModuleContext
) -> None
Handle services healthcheck request.
Parameters:
-
(input_data¤HealthcheckServicesInput) –The input trigger data (unused for healthcheck).
-
(setup_data¤Any) –The setup configuration (unused for healthcheck).
-
(context¤ModuleContext) –The module context.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
healthcheck_status_trigger
¤
Healthcheck status trigger - comprehensive module status.
Classes:
-
HealthcheckStatusTrigger–Handler for comprehensive status healthcheck.
HealthcheckStatusTrigger
¤
HealthcheckStatusTrigger(context: ModuleContext)
flowchart TD
digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger[HealthcheckStatusTrigger]
digitalkin.modules.trigger_handler.TriggerHandler[TriggerHandler]
digitalkin.mixins.base_mixin.BaseMixin[BaseMixin]
digitalkin.mixins.cost_mixin.CostMixin[CostMixin]
digitalkin.mixins.agui_mixin.AgUiMixin[AgUiMixin]
digitalkin.mixins.file_history_mixin.FileHistoryMixin[FileHistoryMixin]
digitalkin.mixins.storage_mixin.StorageMixin[StorageMixin]
digitalkin.mixins.logger_mixin.LoggerMixin[LoggerMixin]
digitalkin.modules.trigger_handler.TriggerHandler --> digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.trigger_handler.TriggerHandler
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.base_mixin.BaseMixin --> digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger
digitalkin.mixins.cost_mixin.CostMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.agui_mixin.AgUiMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.file_history_mixin.FileHistoryMixin --> digitalkin.mixins.base_mixin.BaseMixin
digitalkin.mixins.storage_mixin.StorageMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.file_history_mixin.FileHistoryMixin
digitalkin.mixins.logger_mixin.LoggerMixin --> digitalkin.mixins.base_mixin.BaseMixin
click digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger href "" "digitalkin.modules.triggers.healthcheck_status_trigger.HealthcheckStatusTrigger"
click digitalkin.modules.trigger_handler.TriggerHandler href "" "digitalkin.modules.trigger_handler.TriggerHandler"
click digitalkin.mixins.base_mixin.BaseMixin href "" "digitalkin.mixins.base_mixin.BaseMixin"
click digitalkin.mixins.cost_mixin.CostMixin href "" "digitalkin.mixins.cost_mixin.CostMixin"
click digitalkin.mixins.agui_mixin.AgUiMixin href "" "digitalkin.mixins.agui_mixin.AgUiMixin"
click digitalkin.mixins.file_history_mixin.FileHistoryMixin href "" "digitalkin.mixins.file_history_mixin.FileHistoryMixin"
click digitalkin.mixins.storage_mixin.StorageMixin href "" "digitalkin.mixins.storage_mixin.StorageMixin"
click digitalkin.mixins.logger_mixin.LoggerMixin href "" "digitalkin.mixins.logger_mixin.LoggerMixin"
Handler for comprehensive status healthcheck.
Reports detailed module status including uptime, active jobs, and metadata.
Methods:
-
add_cost–Add a cost entry using the cost strategy.
-
append_files_history–Append files to file history.
-
clear_fh_mission_cache–Remove a mission's entries from in-memory caches after flush.
-
flush_file_history–Flush the current mission's dirty file history to storage.
-
get_cost–Get cost entries for a specific name.
-
get_costs–Get filtered cost entries.
-
handle–Handle status healthcheck request.
-
load_file_history–Load file history for the current session.
-
log_debug–Log debug message using the callbacks strategy.
-
log_error–Log error message using the callbacks strategy.
-
log_info–Log info message using the callbacks strategy.
-
log_warning–Log warning message using the callbacks strategy.
-
read_storage–Read data from storage.
-
send_message–Convert agent event to AG-UI protocol and send via context callbacks.
-
store_storage–Store data using the storage strategy.
-
update_storage–Update existing data in storage.
-
upsert_storage–Insert or update data in storage atomically.
add_cost
async
staticmethod
¤
add_cost(
context: ModuleContext, name: str, cost_config_name: str, quantity: float
) -> None
append_files_history
async
¤
append_files_history(context: ModuleContext, files: list[FileModel]) -> None
Append files to file history.
Files are added to the in-memory cache immediately. A storage write is deferred until the batch threshold is reached (default 10, env: DIGITALKIN_FILE_HISTORY_FLUSH_THRESHOLD) or flush_file_history().
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
-
(files¤list[FileModel]) –List of file models to append.
clear_fh_mission_cache
¤
clear_fh_mission_cache(context: ModuleContext) -> None
Remove a mission's entries from in-memory caches after flush.
Parameters:
-
(context¤ModuleContext) –Module context identifying the mission to clear.
flush_file_history
async
¤
flush_file_history(context: ModuleContext) -> None
Flush the current mission's dirty file history to storage.
Only flushes the key belonging to context's mission_id, preventing cross-mission contamination when handlers are shared.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
get_cost
async
staticmethod
¤
get_costs
async
staticmethod
¤
get_costs(
context: ModuleContext,
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered cost entries.
Parameters:
-
(context¤ModuleContext) –Module context containing the cost strategy.
-
(names¤list[str] | None, default:None) –Optional list of names to filter by.
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –Optional list of cost types to filter by.
Returns:
handle
async
¤
handle(
input_data: HealthcheckStatusInput, setup_data: Any, context: ModuleContext
) -> None
Handle status healthcheck request.
Parameters:
-
(input_data¤HealthcheckStatusInput) –The input trigger data (unused for healthcheck).
-
(setup_data¤Any) –The setup configuration (unused for healthcheck).
-
(context¤ModuleContext) –The module context.
load_file_history
async
¤
load_file_history(context: ModuleContext) -> FileHistory
Load file history for the current session.
Returns cached history on subsequent calls to avoid gRPC reads.
Parameters:
-
(context¤ModuleContext) –Module context containing storage strategy.
Returns:
-
FileHistory–File history object, empty if none exists or loading fails.
log_debug
staticmethod
¤
log_error
staticmethod
¤
log_info
staticmethod
¤
log_warning
staticmethod
¤
read_storage
async
staticmethod
¤
read_storage(
context: ModuleContext, collection: str, record_id: str
) -> StorageRecord | None
Read data from storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
Returns:
-
StorageRecord | None–Retrieved data
Raises:
-
StorageServiceError–If read operation fails
send_message
async
¤
send_message(context: ModuleContext, event: BaseAgentRunEvent) -> None
Convert agent event to AG-UI protocol and send via context callbacks.
Parameters:
-
(context¤ModuleContext) –Module context containing the callbacks strategy.
-
(event¤BaseAgentRunEvent) –Agent run event to process and convert.
store_storage
async
staticmethod
¤
store_storage(
context: ModuleContext,
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Store data using the storage strategy.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name for the data
-
(record_id¤str | None) –Optional record identifier
-
(data¤dict[str, Any]) –Data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–Result from the storage strategy
Raises:
-
StorageServiceError–If storage operation fails
update_storage
async
staticmethod
¤
update_storage(
context: ModuleContext, collection: str, record_id: str, data: dict[str, Any]
) -> StorageRecord | None
Update existing data in storage.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Updated data
Returns:
-
StorageRecord | None–Result from the storage strategy
Raises:
-
StorageServiceError–If update operation fails
upsert_storage
async
staticmethod
¤
upsert_storage(
context: ModuleContext,
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
) -> StorageRecord
Insert or update data in storage atomically.
Parameters:
-
(context¤ModuleContext) –Module context containing the storage strategy
-
(collection¤str) –Collection name
-
(record_id¤str) –Record identifier
-
(data¤dict[str, Any]) –Data to store or update
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –Type of data being stored
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
StorageServiceError–If upsert operation fails
services
¤
This package contains the abstract base class for all services.
Modules:
-
agent–This module is responsible for handling the agent services.
-
base_strategy–This module contains the abstract base class for storage strategies.
-
communication–Communication service for module-to-module interaction.
-
cost–This module is responsible for handling the cost services.
-
filesystem–This module is responsible for handling the filesystem services.
-
identity–This module is responsible for handling the identity service.
-
registry–This module is responsible for handling the registry service.
-
services_config–Service Provider definitions.
-
services_models–This module contains the strategy models for the services.
-
setup–This module is responsible for handling the setup service.
-
snapshot–This module is responsible for handling the snapshot service.
-
storage–This module is responsible for handling the storage service.
-
task_manager–Task manager signal service.
-
user_profile–UserProfile service package.
Classes:
-
AgentStrategy–Abstract base class for agent strategies.
-
CommunicationStrategy–Abstract base class for module-to-module communication.
-
CostStrategy–Abstract base class for cost strategies.
-
DefaultAgent–Default agent implementation for the agent service.
-
DefaultCommunication–Default communication strategy (local implementation).
-
DefaultCost–Default cost strategy.
-
DefaultFilesystem–Default filesystem implementation.
-
DefaultIdentity–DefaultIdentity is the default identity strategy.
-
DefaultRegistry–Default registry strategy using in-memory storage.
-
DefaultSnapshot–Default snapshot strategy.
-
DefaultStorage–Persist records in a local JSON file for quick local development.
-
FilesystemStrategy–Abstract base class for filesystem strategies.
-
GrpcCommunication–gRPC client for module-to-module communication.
-
IdentityStrategy–IdentityStrategy is the abstract base class for all identity strategies.
-
RegistryStrategy–Abstract base class for registry strategies.
-
SnapshotStrategy–Abstract base class for snapshot strategies.
-
StorageStrategy–Define CRUD + list/remove-collection against a collection/record store.
AgentStrategy
¤
AgentStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.AgentStrategy
click digitalkin.services.AgentStrategy href "" "digitalkin.services.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for agent strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
CommunicationStrategy
¤
CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.CommunicationStrategy
click digitalkin.services.CommunicationStrategy href "" "digitalkin.services.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for module-to-module communication.
This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication
The service wraps the Module Service protocol from agentic-mesh-protocol.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
call_module–Call a module and stream responses.
-
close–Release communication resources (channels, connection pools).
-
get_module_schemas–Get module schemas (input/output/setup/secret/cost).
call_module
abstractmethod
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses.
Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close
abstractmethod
async
¤
close() -> None
Release communication resources (channels, connection pools).
get_module_schemas
abstractmethod
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
Get module schemas (input/output/setup/secret/cost).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(llm_format¤bool, default:False) –Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.
Returns:
CostStrategy
¤
CostStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.CostStrategy
click digitalkin.services.CostStrategy href "" "digitalkin.services.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for cost strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
add–Register a new cost.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a cost.
-
get_cost_config–Get cost configuration for the current setup version.
-
get_filtered–Get filtered costs.
-
set_cost_config–Store cost configuration for the current setup version.
-
set_limits–Set cost limits for this session.
add
abstractmethod
async
¤
Register a new cost.
get_cost_config
abstractmethod
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration for the current setup version.
Returns:
-
list[CostConfig]–List of CostConfig objects from the database.
get_filtered
abstractmethod
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered costs.
set_cost_config
abstractmethod
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration for the current setup version.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
abstractmethod
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
DefaultAgent
¤
DefaultAgent(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.DefaultAgent[DefaultAgent]
digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.DefaultAgent
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
click digitalkin.services.DefaultAgent href "" "digitalkin.services.DefaultAgent"
click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default agent implementation for the agent service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
DefaultCommunication
¤
DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.DefaultCommunication[DefaultCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.DefaultCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
click digitalkin.services.DefaultCommunication href "" "digitalkin.services.DefaultCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default communication strategy (local implementation).
This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
Methods:
-
call_module–Call module (local implementation yields empty response).
-
close–No-op for local communication.
-
get_module_schemas–Get module schemas (local implementation returns empty schemas).
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call module (local implementation yields empty response).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data
-
(setup_id¤str) –Setup ID
-
(mission_id¤str) –Mission ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers).
Yields:
-
AsyncGenerator[dict, None]–Empty response dictionary
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
DefaultCost
¤
DefaultCost(
mission_id: str, setup_id: str, setup_version_id: str, config: dict[str, CostConfig]
)
flowchart TD
digitalkin.services.DefaultCost[DefaultCost]
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.DefaultCost
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
click digitalkin.services.DefaultCost href "" "digitalkin.services.DefaultCost"
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default cost strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, CostConfig]) –The configuration dictionary for the cost
Methods:
-
add–Create a new record in the cost database.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a record from the database.
-
get_cost_config–Get cost configuration from in-memory config.
-
get_filtered–Get records from the database.
-
set_cost_config–Store cost configuration in memory.
-
set_limits–Set cost limits for this session.
add
async
¤
get
async
¤
Get a record from the database.
Parameters:
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
get_cost_config
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration from in-memory config.
Returns:
-
list[CostConfig]–List of CostConfig objects from the config dictionary.
get_filtered
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get records from the database.
Parameters:
-
(names¤list[str] | None, default:None) –The names of the costs
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –The types of the costs
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
set_cost_config
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration in memory.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
DefaultFilesystem
¤
DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.DefaultFilesystem[DefaultFilesystem]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.DefaultFilesystem
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
click digitalkin.services.DefaultFilesystem href "" "digitalkin.services.DefaultFilesystem"
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default filesystem implementation.
This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–List files with filtering, sorting, and pagination.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files to delete
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
-
tuple[dict[str, bool], int, int]–tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count
Raises:
-
FilesystemServiceError–If there is an error deleting the files
get_file
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the retrieved file
Raises:
-
FilesystemServiceError–If there is an error retrieving the file
get_files
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
List files with filtering, sorting, and pagination.
This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Fields to order results by (example: "created_at:asc,name:desc")
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files, total count
Raises:
-
FilesystemServiceError–If there is an error listing the files
update_file
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The id of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
Raises:
-
FilesystemServiceError–If there is an error during update
upload_files
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of files to upload
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
Raises:
-
FilesystemServiceError–If there is an error uploading the files
DefaultIdentity
¤
DefaultIdentity(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.DefaultIdentity[DefaultIdentity]
digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.DefaultIdentity
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
click digitalkin.services.DefaultIdentity href "" "digitalkin.services.DefaultIdentity"
click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
DefaultIdentity is the default identity strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
DefaultRegistry
¤
flowchart TD
digitalkin.services.DefaultRegistry[DefaultRegistry]
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.DefaultRegistry
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
click digitalkin.services.DefaultRegistry href "" "digitalkin.services.DefaultRegistry"
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default registry strategy using in-memory storage.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info (not supported in default registry).
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
async
¤
discover_by_id
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
Parameters:
Returns:
-
ModuleInfo–ModuleInfo with module details.
Raises:
-
RegistryModuleNotFoundError–If module not found.
get_setup
async
¤
get_status
async
¤
get_status(module_id: str) -> ModuleStatusInfo
Get module status.
Parameters:
Returns:
-
ModuleStatusInfo–ModuleStatusInfo with current status.
Raises:
-
RegistryModuleNotFoundError–If module not found.
heartbeat
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
async
¤
Register a module with the registry.
Note: Updates existing module or creates new one in local storage.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization (not used in local storage).
Returns:
-
list[ModuleInfo]–List of matching modules.
DefaultSnapshot
¤
DefaultSnapshot(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.DefaultSnapshot[DefaultSnapshot]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.DefaultSnapshot
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
click digitalkin.services.DefaultSnapshot href "" "digitalkin.services.DefaultSnapshot"
click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default snapshot strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
DefaultStorage
¤
DefaultStorage(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
storage_file_path: str = "local_storage",
)
flowchart TD
digitalkin.services.DefaultStorage[DefaultStorage]
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.DefaultStorage
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
click digitalkin.services.DefaultStorage href "" "digitalkin.services.DefaultStorage"
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Persist records in a local JSON file for quick local development.
a JSON object of
{ "
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
FilesystemStrategy
¤
FilesystemStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.FilesystemStrategy
click digitalkin.services.FilesystemStrategy href "" "digitalkin.services.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for filesystem strategies.
This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, Any] | None, default:None) –Configuration for the filesystem strategy
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–Get multiple files by various criteria.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
abstractmethod
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
get_file
abstractmethod
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord–tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content
get_files
abstractmethod
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
Get multiple files by various criteria.
This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Field to order results by
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files and total count
update_file
abstractmethod
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The ID of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
upload_files
abstractmethod
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
GrpcCommunication
¤
GrpcCommunication(
mission_id: str, setup_id: str, setup_version_id: str, client_config: ClientConfig
)
flowchart TD
digitalkin.services.GrpcCommunication[GrpcCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.GrpcCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.GrpcCommunication
click digitalkin.services.GrpcCommunication href "" "digitalkin.services.GrpcCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client for module-to-module communication.
This class provides methods to communicate with remote modules using the Module Service gRPC protocol.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
-
(client_config¤ClientConfig) –Client configuration for gRPC connection
Methods:
-
call_module–Call a module and stream responses via gRPC.
-
close–Release all pooled gRPC channels.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_all_channels–Release refs on all pooled gRPC channels.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_module_schemas–Get module schemas via gRPC.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses via gRPC.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
IdentityStrategy
¤
IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.IdentityStrategy
click digitalkin.services.IdentityStrategy href "" "digitalkin.services.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
IdentityStrategy is the abstract base class for all identity strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
RegistryStrategy
¤
RegistryStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.RegistryStrategy
click digitalkin.services.RegistryStrategy href "" "digitalkin.services.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for registry strategies.
Defines the interface for registry operations including module discovery, registration, and status management.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info.
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
abstractmethod
async
¤
discover_by_id
abstractmethod
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
heartbeat
abstractmethod
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
abstractmethod
async
¤
Register a module with the registry.
Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
abstractmethod
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match via query).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization.
Returns:
-
list[ModuleInfo]–List of matching modules.
SnapshotStrategy
¤
SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.SnapshotStrategy
click digitalkin.services.SnapshotStrategy href "" "digitalkin.services.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for snapshot strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
create
abstractmethod
¤
Create a new snapshot in the file system.
StorageStrategy
¤
StorageStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
)
flowchart TD
digitalkin.services.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.StorageStrategy
click digitalkin.services.StorageStrategy href "" "digitalkin.services.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Define CRUD + list/remove-collection against a collection/record store.
Records are scoped by a context string (the proto field), which is either
self.mission_id (mission scope, the default) or self.setup_version_id
(setup-version scope). Both attributes are expected to already contain the
full prefix (missions:<id> / setup_versions:<id>).
Public methods accept scope: Literal["mission", "setup"] (default
"mission"); internally we resolve it to the matching context string and
pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.
Parameters:
-
(mission_id¤str) –Already-prefixed mission context (
missions:<id>). -
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –Already-prefixed setup-version context (
setup_versions:<id>). -
(config¤dict[str, type[BaseModel]]) –A dictionary mapping names to Pydantic model classes
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
agent
¤
This module is responsible for handling the agent services.
Modules:
-
agent_strategy–This module contains the abstract base class for agent strategies.
-
default_agent–Default agent implementation for the agent service.
Classes:
-
AgentStrategy–Abstract base class for agent strategies.
-
DefaultAgent–Default agent implementation for the agent service.
AgentStrategy
¤
AgentStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.agent.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.AgentStrategy
click digitalkin.services.agent.AgentStrategy href "" "digitalkin.services.agent.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for agent strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
DefaultAgent
¤
DefaultAgent(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.agent.DefaultAgent[DefaultAgent]
digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.agent.DefaultAgent
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
click digitalkin.services.agent.DefaultAgent href "" "digitalkin.services.agent.DefaultAgent"
click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default agent implementation for the agent service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
agent_strategy
¤
This module contains the abstract base class for agent strategies.
Classes:
-
AgentStrategy–Abstract base class for agent strategies.
AgentStrategy
¤
AgentStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for agent strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
default_agent
¤
Default agent implementation for the agent service.
Classes:
-
DefaultAgent–Default agent implementation for the agent service.
DefaultAgent
¤
DefaultAgent(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.agent.default_agent.DefaultAgent[DefaultAgent]
digitalkin.services.agent.agent_strategy.AgentStrategy[AgentStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.agent.agent_strategy.AgentStrategy --> digitalkin.services.agent.default_agent.DefaultAgent
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.agent.agent_strategy.AgentStrategy
click digitalkin.services.agent.default_agent.DefaultAgent href "" "digitalkin.services.agent.default_agent.DefaultAgent"
click digitalkin.services.agent.agent_strategy.AgentStrategy href "" "digitalkin.services.agent.agent_strategy.AgentStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default agent implementation for the agent service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
base_strategy
¤
This module contains the abstract base class for storage strategies.
Classes:
-
BaseStrategy–Abstract base class for all strategies.
BaseStrategy
¤
BaseStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for all strategies.
This class defines the interface for all strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
communication
¤
Communication service for module-to-module interaction.
Modules:
-
communication_strategy–Abstract base class for communication strategies.
-
default_communication–Default communication implementation (local, for testing).
-
grpc_communication–gRPC client implementation for Communication service.
Classes:
-
CommunicationStrategy–Abstract base class for module-to-module communication.
-
DefaultCommunication–Default communication strategy (local implementation).
-
GrpcCommunication–gRPC client for module-to-module communication.
CommunicationStrategy
¤
CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.communication.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.CommunicationStrategy
click digitalkin.services.communication.CommunicationStrategy href "" "digitalkin.services.communication.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for module-to-module communication.
This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication
The service wraps the Module Service protocol from agentic-mesh-protocol.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
call_module–Call a module and stream responses.
-
close–Release communication resources (channels, connection pools).
-
get_module_schemas–Get module schemas (input/output/setup/secret/cost).
call_module
abstractmethod
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses.
Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close
abstractmethod
async
¤
close() -> None
Release communication resources (channels, connection pools).
get_module_schemas
abstractmethod
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
Get module schemas (input/output/setup/secret/cost).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(llm_format¤bool, default:False) –Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.
Returns:
DefaultCommunication
¤
DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.communication.DefaultCommunication[DefaultCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.DefaultCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
click digitalkin.services.communication.DefaultCommunication href "" "digitalkin.services.communication.DefaultCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default communication strategy (local implementation).
This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
Methods:
-
call_module–Call module (local implementation yields empty response).
-
close–No-op for local communication.
-
get_module_schemas–Get module schemas (local implementation returns empty schemas).
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call module (local implementation yields empty response).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data
-
(setup_id¤str) –Setup ID
-
(mission_id¤str) –Mission ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers).
Yields:
-
AsyncGenerator[dict, None]–Empty response dictionary
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
GrpcCommunication
¤
GrpcCommunication(
mission_id: str, setup_id: str, setup_version_id: str, client_config: ClientConfig
)
flowchart TD
digitalkin.services.communication.GrpcCommunication[GrpcCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.GrpcCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.communication.GrpcCommunication
click digitalkin.services.communication.GrpcCommunication href "" "digitalkin.services.communication.GrpcCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client for module-to-module communication.
This class provides methods to communicate with remote modules using the Module Service gRPC protocol.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
-
(client_config¤ClientConfig) –Client configuration for gRPC connection
Methods:
-
call_module–Call a module and stream responses via gRPC.
-
close–Release all pooled gRPC channels.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_all_channels–Release refs on all pooled gRPC channels.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_module_schemas–Get module schemas via gRPC.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses via gRPC.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
communication_strategy
¤
Abstract base class for communication strategies.
Classes:
-
CommunicationStrategy–Abstract base class for module-to-module communication.
CommunicationStrategy
¤
CommunicationStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for module-to-module communication.
This service enables: - Archetype → Tool communication - Archetype → Archetype communication - Tool → Tool communication - Any module → Any module communication
The service wraps the Module Service protocol from agentic-mesh-protocol.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
call_module–Call a module and stream responses.
-
close–Release communication resources (channels, connection pools).
-
get_module_schemas–Get module schemas (input/output/setup/secret/cost).
call_module
abstractmethod
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses.
Uses Module Service StartModule RPC to execute the module. Streams responses as they are generated by the module.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close
abstractmethod
async
¤
close() -> None
Release communication resources (channels, connection pools).
get_module_schemas
abstractmethod
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
Get module schemas (input/output/setup/secret/cost).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(llm_format¤bool, default:False) –Return LLM-friendly format (simplified schema). Note: cost always returns actual data regardless of this flag.
Returns:
default_communication
¤
Default communication implementation (local, for testing).
Classes:
-
DefaultCommunication–Default communication strategy (local implementation).
DefaultCommunication
¤
DefaultCommunication(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.communication.default_communication.DefaultCommunication[DefaultCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.default_communication.DefaultCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
click digitalkin.services.communication.default_communication.DefaultCommunication href "" "digitalkin.services.communication.default_communication.DefaultCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default communication strategy (local implementation).
This implementation is primarily for testing and development. For production, use GrpcCommunication to connect to remote modules.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
Methods:
-
call_module–Call module (local implementation yields empty response).
-
close–No-op for local communication.
-
get_module_schemas–Get module schemas (local implementation returns empty schemas).
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call module (local implementation yields empty response).
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data
-
(setup_id¤str) –Setup ID
-
(mission_id¤str) –Mission ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers).
Yields:
-
AsyncGenerator[dict, None]–Empty response dictionary
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
grpc_communication
¤
gRPC client implementation for Communication service.
Classes:
-
GrpcCommunication–gRPC client for module-to-module communication.
GrpcCommunication
¤
GrpcCommunication(
mission_id: str, setup_id: str, setup_version_id: str, client_config: ClientConfig
)
flowchart TD
digitalkin.services.communication.grpc_communication.GrpcCommunication[GrpcCommunication]
digitalkin.services.communication.communication_strategy.CommunicationStrategy[CommunicationStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.communication.communication_strategy.CommunicationStrategy --> digitalkin.services.communication.grpc_communication.GrpcCommunication
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.communication.communication_strategy.CommunicationStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.communication.grpc_communication.GrpcCommunication
click digitalkin.services.communication.grpc_communication.GrpcCommunication href "" "digitalkin.services.communication.grpc_communication.GrpcCommunication"
click digitalkin.services.communication.communication_strategy.CommunicationStrategy href "" "digitalkin.services.communication.communication_strategy.CommunicationStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client for module-to-module communication.
This class provides methods to communicate with remote modules using the Module Service gRPC protocol.
Parameters:
-
(mission_id¤str) –Mission identifier
-
(setup_id¤str) –Setup identifier
-
(setup_version_id¤str) –Setup version identifier
-
(client_config¤ClientConfig) –Client configuration for gRPC connection
Methods:
-
call_module–Call a module and stream responses via gRPC.
-
close–Release all pooled gRPC channels.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_all_channels–Release refs on all pooled gRPC channels.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_module_schemas–Get module schemas via gRPC.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
call_module
async
¤
call_module(
module_address: str,
module_port: int,
input_data: dict,
setup_id: str,
mission_id: str,
callback: Callable[[dict], Awaitable[None]] | None = None,
metadata: dict[str, str] | None = None,
) -> AsyncGenerator[dict, None]
Call a module and stream responses via gRPC.
Parameters:
-
(module_address¤str) –Target module address
-
(module_port¤int) –Target module port
-
(input_data¤dict) –Input data as dictionary
-
(setup_id¤str) –Setup configuration ID
-
(mission_id¤str) –Mission context ID
-
(callback¤Callable[[dict], Awaitable[None]] | None, default:None) –Optional callback for each response
-
(metadata¤dict[str, str] | None, default:None) –Optional gRPC metadata (headers) to send with the request.
Yields:
-
AsyncGenerator[dict, None]–Streaming responses from module as dictionaries
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_module_schemas
async
¤
get_module_schemas(
module_address: str, module_port: int, *, llm_format: bool = False
) -> dict[str, dict]
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
cost
¤
This module is responsible for handling the cost services.
Modules:
-
cost_strategy–This module contains the abstract base class for cost strategies.
-
default_cost–Default cost.
-
grpc_cost–This module implements the gRPC Cost strategy.
Classes:
-
CostConfig–Pydantic model that defines a cost configuration.
-
CostData–Data model for cost operations.
-
CostStrategy–Abstract base class for cost strategies.
-
CostType–Enum defining the types of costs that can be registered.
-
DefaultCost–Default cost strategy.
-
GrpcCost–gRPC client implementation for the Cost service.
CostConfig
¤
flowchart TD
digitalkin.services.cost.CostConfig[CostConfig]
click digitalkin.services.cost.CostConfig href "" "digitalkin.services.cost.CostConfig"
Pydantic model that defines a cost configuration.
:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).
CostData
¤
flowchart TD
digitalkin.services.cost.CostData[CostData]
click digitalkin.services.cost.CostData href "" "digitalkin.services.cost.CostData"
Data model for cost operations.
CostStrategy
¤
CostStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.cost.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.CostStrategy
click digitalkin.services.cost.CostStrategy href "" "digitalkin.services.cost.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for cost strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
add–Register a new cost.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a cost.
-
get_cost_config–Get cost configuration for the current setup version.
-
get_filtered–Get filtered costs.
-
set_cost_config–Store cost configuration for the current setup version.
-
set_limits–Set cost limits for this session.
add
abstractmethod
async
¤
Register a new cost.
get_cost_config
abstractmethod
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration for the current setup version.
Returns:
-
list[CostConfig]–List of CostConfig objects from the database.
get_filtered
abstractmethod
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered costs.
set_cost_config
abstractmethod
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration for the current setup version.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
abstractmethod
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
CostType
¤
flowchart TD
digitalkin.services.cost.CostType[CostType]
click digitalkin.services.cost.CostType href "" "digitalkin.services.cost.CostType"
Enum defining the types of costs that can be registered.
DefaultCost
¤
DefaultCost(
mission_id: str, setup_id: str, setup_version_id: str, config: dict[str, CostConfig]
)
flowchart TD
digitalkin.services.cost.DefaultCost[DefaultCost]
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.DefaultCost
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
click digitalkin.services.cost.DefaultCost href "" "digitalkin.services.cost.DefaultCost"
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default cost strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, CostConfig]) –The configuration dictionary for the cost
Methods:
-
add–Create a new record in the cost database.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a record from the database.
-
get_cost_config–Get cost configuration from in-memory config.
-
get_filtered–Get records from the database.
-
set_cost_config–Store cost configuration in memory.
-
set_limits–Set cost limits for this session.
add
async
¤
get
async
¤
Get a record from the database.
Parameters:
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
get_cost_config
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration from in-memory config.
Returns:
-
list[CostConfig]–List of CostConfig objects from the config dictionary.
get_filtered
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get records from the database.
Parameters:
-
(names¤list[str] | None, default:None) –The names of the costs
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –The types of the costs
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
set_cost_config
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration in memory.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
GrpcCost
¤
GrpcCost(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, CostConfig],
client_config: ClientConfig,
)
flowchart TD
digitalkin.services.cost.GrpcCost[GrpcCost]
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.GrpcCost
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.cost.GrpcCost
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.cost.GrpcCost
click digitalkin.services.cost.GrpcCost href "" "digitalkin.services.cost.GrpcCost"
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the Cost service.
Methods:
-
add–Create a new record in the cost database.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get–Get a record from the database.
-
get_cost_config–Get cost configuration from the database.
-
get_filtered–Get a list of records from the database.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
set_cost_config–Store cost configuration in the database.
-
set_limits–Set cost limits for this session.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
add
async
¤
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get
async
¤
get_cost_config
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration from the database.
Returns:
-
list[CostConfig]–List of CostConfig objects from the database.
get_filtered
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
set_cost_config
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration in the database.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
cost_strategy
¤
This module contains the abstract base class for cost strategies.
Classes:
-
CostConfig–Pydantic model that defines a cost configuration.
-
CostData–Data model for cost operations.
-
CostServiceError–Custom exception for CostService errors.
-
CostStrategy–Abstract base class for cost strategies.
-
CostType–Enum defining the types of costs that can be registered.
CostConfig
¤
flowchart TD
digitalkin.services.cost.cost_strategy.CostConfig[CostConfig]
click digitalkin.services.cost.cost_strategy.CostConfig href "" "digitalkin.services.cost.cost_strategy.CostConfig"
Pydantic model that defines a cost configuration.
:param cost_name: Name of the cost (unique identifier in the service). :param cost_type: The type/category of the cost. :param description: A short description of the cost. :param unit: The unit of measurement (e.g. token, call, MB). :param rate: The cost per unit (e.g. dollars per token).
CostData
¤
flowchart TD
digitalkin.services.cost.cost_strategy.CostData[CostData]
click digitalkin.services.cost.cost_strategy.CostData href "" "digitalkin.services.cost.cost_strategy.CostData"
Data model for cost operations.
CostServiceError
¤
flowchart TD
digitalkin.services.cost.cost_strategy.CostServiceError[CostServiceError]
click digitalkin.services.cost.cost_strategy.CostServiceError href "" "digitalkin.services.cost.cost_strategy.CostServiceError"
Custom exception for CostService errors.
CostStrategy
¤
CostStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for cost strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
add–Register a new cost.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a cost.
-
get_cost_config–Get cost configuration for the current setup version.
-
get_filtered–Get filtered costs.
-
set_cost_config–Store cost configuration for the current setup version.
-
set_limits–Set cost limits for this session.
add
abstractmethod
async
¤
Register a new cost.
get_cost_config
abstractmethod
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration for the current setup version.
Returns:
-
list[CostConfig]–List of CostConfig objects from the database.
get_filtered
abstractmethod
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get filtered costs.
set_cost_config
abstractmethod
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration for the current setup version.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
abstractmethod
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
CostType
¤
flowchart TD
digitalkin.services.cost.cost_strategy.CostType[CostType]
click digitalkin.services.cost.cost_strategy.CostType href "" "digitalkin.services.cost.cost_strategy.CostType"
Enum defining the types of costs that can be registered.
default_cost
¤
Default cost.
Classes:
-
DefaultCost–Default cost strategy.
DefaultCost
¤
DefaultCost(
mission_id: str, setup_id: str, setup_version_id: str, config: dict[str, CostConfig]
)
flowchart TD
digitalkin.services.cost.default_cost.DefaultCost[DefaultCost]
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.default_cost.DefaultCost
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
click digitalkin.services.cost.default_cost.DefaultCost href "" "digitalkin.services.cost.default_cost.DefaultCost"
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default cost strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, CostConfig]) –The configuration dictionary for the cost
Methods:
-
add–Create a new record in the cost database.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
get–Get a record from the database.
-
get_cost_config–Get cost configuration from in-memory config.
-
get_filtered–Get records from the database.
-
set_cost_config–Store cost configuration in memory.
-
set_limits–Set cost limits for this session.
add
async
¤
get
async
¤
Get a record from the database.
Parameters:
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
get_cost_config
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration from in-memory config.
Returns:
-
list[CostConfig]–List of CostConfig objects from the config dictionary.
get_filtered
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
Get records from the database.
Parameters:
-
(names¤list[str] | None, default:None) –The names of the costs
-
(cost_types¤list[Literal['TOKEN_INPUT', 'TOKEN_OUTPUT', 'API_CALL', 'STORAGE', 'TIME', 'OTHER']] | None, default:None) –The types of the costs
Returns:
Raises:
-
CostServiceError–If the cost data is invalid or if the cost does not exist
set_cost_config
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration in memory.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
grpc_cost
¤
This module implements the gRPC Cost strategy.
Classes:
-
GrpcCost–gRPC client implementation for the Cost service.
GrpcCost
¤
GrpcCost(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, CostConfig],
client_config: ClientConfig,
)
flowchart TD
digitalkin.services.cost.grpc_cost.GrpcCost[GrpcCost]
digitalkin.services.cost.cost_strategy.CostStrategy[CostStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.cost.cost_strategy.CostStrategy --> digitalkin.services.cost.grpc_cost.GrpcCost
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.cost.cost_strategy.CostStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.cost.grpc_cost.GrpcCost
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.cost.grpc_cost.GrpcCost
click digitalkin.services.cost.grpc_cost.GrpcCost href "" "digitalkin.services.cost.grpc_cost.GrpcCost"
click digitalkin.services.cost.cost_strategy.CostStrategy href "" "digitalkin.services.cost.cost_strategy.CostStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the Cost service.
Methods:
-
add–Create a new record in the cost database.
-
check_limit–Check if adding this cost would exceed any limits.
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get–Get a record from the database.
-
get_cost_config–Get cost configuration from the database.
-
get_filtered–Get a list of records from the database.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
set_cost_config–Store cost configuration in the database.
-
set_limits–Set cost limits for this session.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
add
async
¤
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get
async
¤
get_cost_config
async
¤
get_cost_config() -> list[CostConfig]
Get cost configuration from the database.
Returns:
-
list[CostConfig]–List of CostConfig objects from the database.
get_filtered
async
¤
get_filtered(
names: list[str] | None = None,
cost_types: list[
Literal["TOKEN_INPUT", "TOKEN_OUTPUT", "API_CALL", "STORAGE", "TIME", "OTHER"]
]
| None = None,
) -> list[CostData]
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
set_cost_config
async
¤
set_cost_config(configs: list[CostConfig]) -> bool
Store cost configuration in the database.
Parameters:
-
(configs¤list[CostConfig]) –List of CostConfig objects to store.
Returns:
-
bool–True if successfully stored.
set_limits
async
¤
set_limits(limits: list[QuantityLimit | AmountLimit]) -> None
Set cost limits for this session.
Parameters:
-
(limits¤list[QuantityLimit | AmountLimit]) –List of CostLimit objects to enforce.
filesystem
¤
This module is responsible for handling the filesystem services.
Modules:
-
default_filesystem–Default filesystem implementation.
-
filesystem_strategy–This module contains the abstract base class for filesystem strategies.
-
grpc_filesystem–gRPC filesystem implementation.
Classes:
-
DefaultFilesystem–Default filesystem implementation.
-
FilesystemStrategy–Abstract base class for filesystem strategies.
-
GrpcFilesystem–gRPC client implementation for the Filesystem service.
DefaultFilesystem
¤
DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.filesystem.DefaultFilesystem[DefaultFilesystem]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.DefaultFilesystem
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
click digitalkin.services.filesystem.DefaultFilesystem href "" "digitalkin.services.filesystem.DefaultFilesystem"
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default filesystem implementation.
This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–List files with filtering, sorting, and pagination.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files to delete
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
-
tuple[dict[str, bool], int, int]–tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count
Raises:
-
FilesystemServiceError–If there is an error deleting the files
get_file
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the retrieved file
Raises:
-
FilesystemServiceError–If there is an error retrieving the file
get_files
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
List files with filtering, sorting, and pagination.
This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Fields to order results by (example: "created_at:asc,name:desc")
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files, total count
Raises:
-
FilesystemServiceError–If there is an error listing the files
update_file
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The id of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
Raises:
-
FilesystemServiceError–If there is an error during update
upload_files
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of files to upload
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
Raises:
-
FilesystemServiceError–If there is an error uploading the files
FilesystemStrategy
¤
FilesystemStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.filesystem.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.FilesystemStrategy
click digitalkin.services.filesystem.FilesystemStrategy href "" "digitalkin.services.filesystem.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for filesystem strategies.
This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, Any] | None, default:None) –Configuration for the filesystem strategy
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–Get multiple files by various criteria.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
abstractmethod
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
get_file
abstractmethod
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord–tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content
get_files
abstractmethod
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
Get multiple files by various criteria.
This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Field to order results by
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files and total count
update_file
abstractmethod
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The ID of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
upload_files
abstractmethod
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
GrpcFilesystem
¤
GrpcFilesystem(
mission_id: str,
setup_id: str,
setup_version_id: str,
client_config: ClientConfig,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.filesystem.GrpcFilesystem[GrpcFilesystem]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.GrpcFilesystem
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.filesystem.GrpcFilesystem
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.filesystem.GrpcFilesystem
click digitalkin.services.filesystem.GrpcFilesystem href "" "digitalkin.services.filesystem.GrpcFilesystem"
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the Filesystem service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(client_config¤ClientConfig) –Configuration for the gRPC client connection
-
(config¤dict[str, Any] | None, default:None) –Configuration for the filesystem strategy
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
delete_files–Delete multiple files from the filesystem.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_file–Get a file from the filesystem.
-
get_files–Get multiple files from the filesystem.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
update_file–Update a file in the filesystem.
-
upload_files–Upload multiple files to the filesystem.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
delete_files
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_file
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a file from the filesystem.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the retrieved file
Raises:
-
FilesystemServiceError–If there is an error retrieving the file
get_files
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
Get multiple files from the filesystem.
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start from
-
(order¤str | None, default:None) –Field to order results by
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files and total count
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
update_file
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update a file in the filesystem.
Parameters:
-
(file_id¤str) –The id of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
Raises:
-
FilesystemServiceError–If there is an error during update
upload_files
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the filesystem.
Parameters:
-
(files¤list[UploadFileData]) –List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
default_filesystem
¤
Default filesystem implementation.
Classes:
-
DefaultFilesystem–Default filesystem implementation.
DefaultFilesystem
¤
DefaultFilesystem(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.filesystem.default_filesystem.DefaultFilesystem[DefaultFilesystem]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.default_filesystem.DefaultFilesystem
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
click digitalkin.services.filesystem.default_filesystem.DefaultFilesystem href "" "digitalkin.services.filesystem.default_filesystem.DefaultFilesystem"
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default filesystem implementation.
This implementation provides a local filesystem-based storage solution with support for all filesystem operations defined in the strategy. Files are stored in a temporary directory with proper metadata tracking.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–List files with filtering, sorting, and pagination.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files to delete
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
-
tuple[dict[str, bool], int, int]–tuple[dict[str, bool], int, int]: Results per file, total deleted count, total failed count
Raises:
-
FilesystemServiceError–If there is an error deleting the files
get_file
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the retrieved file
Raises:
-
FilesystemServiceError–If there is an error retrieving the file
get_files
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
List files with filtering, sorting, and pagination.
This method provides flexible file querying capabilities with support for: - Multiple filter criteria (name, type, dates, size, etc.) - Pagination for large result sets - Sorting by various fields - Scoped access by context
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Fields to order results by (example: "created_at:asc,name:desc")
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files, total count
Raises:
-
FilesystemServiceError–If there is an error listing the files
update_file
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The id of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
Raises:
-
FilesystemServiceError–If there is an error during update
upload_files
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of files to upload
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
Raises:
-
FilesystemServiceError–If there is an error uploading the files
filesystem_strategy
¤
This module contains the abstract base class for filesystem strategies.
Classes:
-
FileFilter–Filter criteria for querying files.
-
FilesystemRecord–Data model for filesystem operations.
-
FilesystemServiceError–Base exception for Filesystem service errors.
-
FilesystemStrategy–Abstract base class for filesystem strategies.
-
UploadFileData–Data model for uploading a file.
FileFilter
¤
flowchart TD
digitalkin.services.filesystem.filesystem_strategy.FileFilter[FileFilter]
click digitalkin.services.filesystem.filesystem_strategy.FileFilter href "" "digitalkin.services.filesystem.filesystem_strategy.FileFilter"
Filter criteria for querying files.
FilesystemRecord
¤
flowchart TD
digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord[FilesystemRecord]
click digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemRecord"
Data model for filesystem operations.
FilesystemServiceError
¤
flowchart TD
digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError[FilesystemServiceError]
click digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemServiceError"
Base exception for Filesystem service errors.
FilesystemStrategy
¤
FilesystemStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for filesystem strategies.
This strategy provides comprehensive file management capabilities including upload, retrieval, update, and deletion operations with rich metadata support, filtering, and pagination.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(config¤dict[str, Any] | None, default:None) –Configuration for the filesystem strategy
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
delete_files–Delete multiple files.
-
get_file–Get a specific file by ID or name.
-
get_files–Get multiple files by various criteria.
-
update_file–Update file metadata, content, or both.
-
upload_files–Upload multiple files to the system.
delete_files
abstractmethod
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
Delete multiple files.
This method supports batch deletion of files with options for: - Soft deletion (marking as deleted) - Permanent deletion - Force deletion of files in use - Individual error reporting per file
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(permanent¤bool, default:False) –Whether to permanently delete the files
-
(force¤bool, default:False) –Whether to force delete even if files are in use
Returns:
get_file
abstractmethod
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a specific file by ID or name.
This method fetches detailed information about a single file, with optional content inclusion. Supports lookup by either unique ID or name within a context.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord–tuple[FilesystemRecord, bytes | None]: Metadata about the retrieved file and optional content
get_files
abstractmethod
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
Get multiple files by various criteria.
This method provides efficient retrieval of multiple files using: - File IDs - File names - Path prefix With support for: - Pagination for large result sets - Optional content inclusion - Total count of matching files
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start listing files from
-
(order¤str | None, default:None) –Field to order results by
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files and total count
update_file
abstractmethod
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update file metadata, content, or both.
This method allows updating various aspects of a file: - Rename files - Update content and content type - Modify metadata - Create new versions
Parameters:
-
(file_id¤str) –The ID of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
upload_files
abstractmethod
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the system.
This method allows batch uploading of files with validation and error handling for each individual file. Files are processed atomically - if one fails, others may still succeed.
Parameters:
-
(files¤list[UploadFileData]) –List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
UploadFileData
¤
flowchart TD
digitalkin.services.filesystem.filesystem_strategy.UploadFileData[UploadFileData]
click digitalkin.services.filesystem.filesystem_strategy.UploadFileData href "" "digitalkin.services.filesystem.filesystem_strategy.UploadFileData"
Data model for uploading a file.
grpc_filesystem
¤
gRPC filesystem implementation.
Classes:
-
GrpcFilesystem–gRPC client implementation for the Filesystem service.
GrpcFilesystem
¤
GrpcFilesystem(
mission_id: str,
setup_id: str,
setup_version_id: str,
client_config: ClientConfig,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem[GrpcFilesystem]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy[FilesystemStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem
click digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem href "" "digitalkin.services.filesystem.grpc_filesystem.GrpcFilesystem"
click digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy href "" "digitalkin.services.filesystem.filesystem_strategy.FilesystemStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the Filesystem service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
-
(client_config¤ClientConfig) –Configuration for the gRPC client connection
-
(config¤dict[str, Any] | None, default:None) –Configuration for the filesystem strategy
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
delete_files–Delete multiple files from the filesystem.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_file–Get a file from the filesystem.
-
get_files–Get multiple files from the filesystem.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
update_file–Update a file in the filesystem.
-
upload_files–Upload multiple files to the filesystem.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
delete_files
async
¤
delete_files(
filters: FileFilter, *, permanent: bool = False, force: bool = False
) -> tuple[dict[str, bool], int, int]
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_file
async
¤
get_file(
file_id: str,
context: Literal["mission", "setup"] = "mission",
*,
include_content: bool = False,
) -> FilesystemRecord
Get a file from the filesystem.
Parameters:
-
(file_id¤str) –The ID of the file to be retrieved
-
(context¤Literal['mission', 'setup'], default:'mission') –The context of the files (mission or setup)
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the retrieved file
Raises:
-
FilesystemServiceError–If there is an error retrieving the file
get_files
async
¤
get_files(
filters: FileFilter,
*,
list_size: int = 100,
offset: int = 0,
order: str | None = None,
include_content: bool = False,
) -> tuple[list[FilesystemRecord], int]
Get multiple files from the filesystem.
Parameters:
-
(filters¤FileFilter) –Filter criteria for the files
-
(list_size¤int, default:100) –Number of files to return per page
-
(offset¤int, default:0) –Offset to start from
-
(order¤str | None, default:None) –Field to order results by
-
(include_content¤bool, default:False) –Whether to include file content in response
Returns:
-
tuple[list[FilesystemRecord], int]–tuple[list[FilesystemRecord], int]: List of files and total count
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
update_file
async
¤
update_file(
file_id: str,
content: bytes | None = None,
file_type: Literal[
"UNSPECIFIED", "DOCUMENT", "IMAGE", "VIDEO", "AUDIO", "ARCHIVE", "CODE", "OTHER"
]
| None = None,
content_type: str | None = None,
metadata: dict[str, Any] | None = None,
new_name: str | None = None,
status: str | None = None,
) -> FilesystemRecord
Update a file in the filesystem.
Parameters:
-
(file_id¤str) –The id of the file to be updated
-
(content¤bytes | None, default:None) –Optional new content of the file
-
(file_type¤Literal['UNSPECIFIED', 'DOCUMENT', 'IMAGE', 'VIDEO', 'AUDIO', 'ARCHIVE', 'CODE', 'OTHER'] | None, default:None) –Optional new type of data
-
(content_type¤str | None, default:None) –Optional new MIME type
-
(metadata¤dict[str, Any] | None, default:None) –Optional new metadata (will merge with existing)
-
(new_name¤str | None, default:None) –Optional new name for the file
-
(status¤str | None, default:None) –Optional new status for the file
Returns:
-
FilesystemRecord(FilesystemRecord) –Metadata about the updated file
Raises:
-
FilesystemServiceError–If there is an error during update
upload_files
async
¤
upload_files(files: list[UploadFileData]) -> tuple[list[FilesystemRecord], int, int]
Upload multiple files to the filesystem.
Parameters:
-
(files¤list[UploadFileData]) –List of tuples containing (content, name, file_type, content_type, metadata, replace_if_exists)
Returns:
-
tuple[list[FilesystemRecord], int, int]–tuple[list[FilesystemRecord], int, int]: List of uploaded files, total uploaded count, total failed count
identity
¤
This module is responsible for handling the identity service.
Modules:
-
default_identity–Default identity.
-
identity_strategy–This module contains the abstract base class for identity strategies.
Classes:
-
DefaultIdentity–DefaultIdentity is the default identity strategy.
-
IdentityStrategy–IdentityStrategy is the abstract base class for all identity strategies.
DefaultIdentity
¤
DefaultIdentity(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.identity.DefaultIdentity[DefaultIdentity]
digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.identity.DefaultIdentity
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
click digitalkin.services.identity.DefaultIdentity href "" "digitalkin.services.identity.DefaultIdentity"
click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
DefaultIdentity is the default identity strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
IdentityStrategy
¤
IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.identity.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.IdentityStrategy
click digitalkin.services.identity.IdentityStrategy href "" "digitalkin.services.identity.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
IdentityStrategy is the abstract base class for all identity strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
default_identity
¤
Default identity.
Classes:
-
DefaultIdentity–DefaultIdentity is the default identity strategy.
DefaultIdentity
¤
DefaultIdentity(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.identity.default_identity.DefaultIdentity[DefaultIdentity]
digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.identity.identity_strategy.IdentityStrategy --> digitalkin.services.identity.default_identity.DefaultIdentity
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
click digitalkin.services.identity.default_identity.DefaultIdentity href "" "digitalkin.services.identity.default_identity.DefaultIdentity"
click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
DefaultIdentity is the default identity strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
identity_strategy
¤
This module contains the abstract base class for identity strategies.
Classes:
-
IdentityStrategy–IdentityStrategy is the abstract base class for all identity strategies.
IdentityStrategy
¤
IdentityStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.identity.identity_strategy.IdentityStrategy[IdentityStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.identity.identity_strategy.IdentityStrategy
click digitalkin.services.identity.identity_strategy.IdentityStrategy href "" "digitalkin.services.identity.identity_strategy.IdentityStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
IdentityStrategy is the abstract base class for all identity strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_identity–Get the identity.
registry
¤
This module is responsible for handling the registry service.
Modules:
-
default_registry–Default registry implementation.
-
exceptions–Registry-specific exceptions.
-
grpc_registry–gRPC Registry client implementation.
-
registry_models–Registry data models.
-
registry_strategy–Abstract base class for registry strategies.
Classes:
-
DefaultRegistry–Default registry strategy using in-memory storage.
-
GrpcRegistry–gRPC-based registry client.
-
ModuleInfo–Module information from registry.
-
ModuleStatusInfo–Module status response.
-
RegistryModuleNotFoundError–Raised when a module is not found in the registry.
-
RegistryModuleStatus–Module status in the registry.
-
RegistryModuleType–Module type in the registry.
-
RegistryServiceError–Base exception for registry service errors.
-
RegistryStrategy–Abstract base class for registry strategies.
DefaultRegistry
¤
flowchart TD
digitalkin.services.registry.DefaultRegistry[DefaultRegistry]
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.DefaultRegistry
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
click digitalkin.services.registry.DefaultRegistry href "" "digitalkin.services.registry.DefaultRegistry"
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default registry strategy using in-memory storage.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info (not supported in default registry).
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
async
¤
discover_by_id
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
Parameters:
Returns:
-
ModuleInfo–ModuleInfo with module details.
Raises:
-
RegistryModuleNotFoundError–If module not found.
get_setup
async
¤
get_status
async
¤
get_status(module_id: str) -> ModuleStatusInfo
Get module status.
Parameters:
Returns:
-
ModuleStatusInfo–ModuleStatusInfo with current status.
Raises:
-
RegistryModuleNotFoundError–If module not found.
heartbeat
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
async
¤
Register a module with the registry.
Note: Updates existing module or creates new one in local storage.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization (not used in local storage).
Returns:
-
list[ModuleInfo]–List of matching modules.
GrpcRegistry
¤
GrpcRegistry(
mission_id: str,
setup_id: str,
setup_version_id: str,
client_config: ClientConfig,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.registry.GrpcRegistry[GrpcRegistry]
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.GrpcRegistry
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.registry.GrpcRegistry
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.registry.GrpcRegistry
click digitalkin.services.registry.GrpcRegistry href "" "digitalkin.services.registry.GrpcRegistry"
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC-based registry client.
This client communicates with the Service Provider's Registry service to perform module discovery, registration, and status management operations.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_setup–Get setup info.
-
get_status–Get module status by fetching the module.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
heartbeat–Send heartbeat to keep module active.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
register–Register a module with the registry.
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
deregister
async
¤
Deregister a module from the registry.
Note: The registry protocol uses heartbeat expiration for deregistration. When a module stops sending heartbeats, it becomes inactive. This method logs the deregistration intent for observability.
Parameters:
Returns:
-
bool–True always (heartbeat expiration handles actual deregistration).
discover_by_id
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
Parameters:
Returns:
-
ModuleInfo–ModuleInfo with module details.
Raises:
-
RegistryModuleNotFoundError–If module not found.
-
RegistryServiceError–If gRPC call fails.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_setup
async
¤
Get setup info.
Parameters:
Returns:
-
SetupInfo | None–SetupInfo if successful, None otherwise.
Raises:
-
RegistryServiceError–If gRPC call fails.
get_status
async
¤
get_status(module_id: str) -> ModuleStatusInfo
Get module status by fetching the module.
Parameters:
Returns:
-
ModuleStatusInfo–ModuleStatusInfo with current status.
Raises:
-
RegistryModuleNotFoundError–If module not found.
-
RegistryServiceError–If gRPC call fails.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
heartbeat
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryServiceError–If gRPC call fails.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
register
async
¤
Register a module with the registry.
Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None if module not found.
Raises:
-
RegistryServiceError–If gRPC call fails.
release_cached_channel
async
classmethod
¤
search
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match via query).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization.
Returns:
-
list[ModuleInfo]–List of matching modules.
Raises:
-
RegistryServiceError–If gRPC call fails.
ModuleInfo
¤
flowchart TD
digitalkin.services.registry.ModuleInfo[ModuleInfo]
click digitalkin.services.registry.ModuleInfo href "" "digitalkin.services.registry.ModuleInfo"
Module information from registry.
ModuleStatusInfo
¤
flowchart TD
digitalkin.services.registry.ModuleStatusInfo[ModuleStatusInfo]
click digitalkin.services.registry.ModuleStatusInfo href "" "digitalkin.services.registry.ModuleStatusInfo"
Module status response.
RegistryModuleNotFoundError
¤
flowchart TD
digitalkin.services.registry.RegistryModuleNotFoundError[RegistryModuleNotFoundError]
digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]
digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.RegistryModuleNotFoundError
click digitalkin.services.registry.RegistryModuleNotFoundError href "" "digitalkin.services.registry.RegistryModuleNotFoundError"
click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
Raised when a module is not found in the registry.
Parameters:
RegistryModuleStatus
¤
flowchart TD
digitalkin.services.registry.RegistryModuleStatus[RegistryModuleStatus]
click digitalkin.services.registry.RegistryModuleStatus href "" "digitalkin.services.registry.RegistryModuleStatus"
Module status in the registry.
RegistryModuleType
¤
flowchart TD
digitalkin.services.registry.RegistryModuleType[RegistryModuleType]
click digitalkin.services.registry.RegistryModuleType href "" "digitalkin.services.registry.RegistryModuleType"
Module type in the registry.
RegistryServiceError
¤
flowchart TD
digitalkin.services.registry.RegistryServiceError[RegistryServiceError]
click digitalkin.services.registry.RegistryServiceError href "" "digitalkin.services.registry.RegistryServiceError"
Base exception for registry service errors.
RegistryStrategy
¤
RegistryStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.registry.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.RegistryStrategy
click digitalkin.services.registry.RegistryStrategy href "" "digitalkin.services.registry.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for registry strategies.
Defines the interface for registry operations including module discovery, registration, and status management.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info.
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
abstractmethod
async
¤
discover_by_id
abstractmethod
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
heartbeat
abstractmethod
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
abstractmethod
async
¤
Register a module with the registry.
Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
abstractmethod
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match via query).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization.
Returns:
-
list[ModuleInfo]–List of matching modules.
default_registry
¤
Default registry implementation.
Classes:
-
DefaultRegistry–Default registry strategy using in-memory storage.
DefaultRegistry
¤
flowchart TD
digitalkin.services.registry.default_registry.DefaultRegistry[DefaultRegistry]
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.default_registry.DefaultRegistry
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
click digitalkin.services.registry.default_registry.DefaultRegistry href "" "digitalkin.services.registry.default_registry.DefaultRegistry"
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default registry strategy using in-memory storage.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info (not supported in default registry).
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
async
¤
discover_by_id
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
Parameters:
Returns:
-
ModuleInfo–ModuleInfo with module details.
Raises:
-
RegistryModuleNotFoundError–If module not found.
get_setup
async
¤
get_status
async
¤
get_status(module_id: str) -> ModuleStatusInfo
Get module status.
Parameters:
Returns:
-
ModuleStatusInfo–ModuleStatusInfo with current status.
Raises:
-
RegistryModuleNotFoundError–If module not found.
heartbeat
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
async
¤
Register a module with the registry.
Note: Updates existing module or creates new one in local storage.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization (not used in local storage).
Returns:
-
list[ModuleInfo]–List of matching modules.
exceptions
¤
Registry-specific exceptions.
This module contains custom exceptions for registry service operations.
Classes:
-
InvalidStatusError–Raised when an invalid status is provided.
-
ModuleAlreadyExistsError–Raised when attempting to register an already-registered module.
-
RegistryModuleNotFoundError–Raised when a module is not found in the registry.
-
RegistryServiceError–Base exception for registry service errors.
InvalidStatusError
¤
flowchart TD
digitalkin.services.registry.exceptions.InvalidStatusError[InvalidStatusError]
digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]
digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.InvalidStatusError
click digitalkin.services.registry.exceptions.InvalidStatusError href "" "digitalkin.services.registry.exceptions.InvalidStatusError"
click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
Raised when an invalid status is provided.
Parameters:
ModuleAlreadyExistsError
¤
flowchart TD
digitalkin.services.registry.exceptions.ModuleAlreadyExistsError[ModuleAlreadyExistsError]
digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]
digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.ModuleAlreadyExistsError
click digitalkin.services.registry.exceptions.ModuleAlreadyExistsError href "" "digitalkin.services.registry.exceptions.ModuleAlreadyExistsError"
click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
Raised when attempting to register an already-registered module.
Parameters:
RegistryModuleNotFoundError
¤
flowchart TD
digitalkin.services.registry.exceptions.RegistryModuleNotFoundError[RegistryModuleNotFoundError]
digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]
digitalkin.services.registry.exceptions.RegistryServiceError --> digitalkin.services.registry.exceptions.RegistryModuleNotFoundError
click digitalkin.services.registry.exceptions.RegistryModuleNotFoundError href "" "digitalkin.services.registry.exceptions.RegistryModuleNotFoundError"
click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
Raised when a module is not found in the registry.
Parameters:
RegistryServiceError
¤
flowchart TD
digitalkin.services.registry.exceptions.RegistryServiceError[RegistryServiceError]
click digitalkin.services.registry.exceptions.RegistryServiceError href "" "digitalkin.services.registry.exceptions.RegistryServiceError"
Base exception for registry service errors.
grpc_registry
¤
gRPC Registry client implementation.
This module provides a gRPC-based registry client that communicates with the Service Provider's Registry service.
Classes:
-
GrpcRegistry–gRPC-based registry client.
GrpcRegistry
¤
GrpcRegistry(
mission_id: str,
setup_id: str,
setup_version_id: str,
client_config: ClientConfig,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.registry.grpc_registry.GrpcRegistry[GrpcRegistry]
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.registry.registry_strategy.RegistryStrategy --> digitalkin.services.registry.grpc_registry.GrpcRegistry
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.registry.grpc_registry.GrpcRegistry
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.registry.grpc_registry.GrpcRegistry
click digitalkin.services.registry.grpc_registry.GrpcRegistry href "" "digitalkin.services.registry.grpc_registry.GrpcRegistry"
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC-based registry client.
This client communicates with the Service Provider's Registry service to perform module discovery, registration, and status management operations.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_setup–Get setup info.
-
get_status–Get module status by fetching the module.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
heartbeat–Send heartbeat to keep module active.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
register–Register a module with the registry.
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
deregister
async
¤
Deregister a module from the registry.
Note: The registry protocol uses heartbeat expiration for deregistration. When a module stops sending heartbeats, it becomes inactive. This method logs the deregistration intent for observability.
Parameters:
Returns:
-
bool–True always (heartbeat expiration handles actual deregistration).
discover_by_id
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
Parameters:
Returns:
-
ModuleInfo–ModuleInfo with module details.
Raises:
-
RegistryModuleNotFoundError–If module not found.
-
RegistryServiceError–If gRPC call fails.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_setup
async
¤
Get setup info.
Parameters:
Returns:
-
SetupInfo | None–SetupInfo if successful, None otherwise.
Raises:
-
RegistryServiceError–If gRPC call fails.
get_status
async
¤
get_status(module_id: str) -> ModuleStatusInfo
Get module status by fetching the module.
Parameters:
Returns:
-
ModuleStatusInfo–ModuleStatusInfo with current status.
Raises:
-
RegistryModuleNotFoundError–If module not found.
-
RegistryServiceError–If gRPC call fails.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
heartbeat
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryServiceError–If gRPC call fails.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
register
async
¤
Register a module with the registry.
Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None if module not found.
Raises:
-
RegistryServiceError–If gRPC call fails.
release_cached_channel
async
classmethod
¤
search
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match via query).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization.
Returns:
-
list[ModuleInfo]–List of matching modules.
Raises:
-
RegistryServiceError–If gRPC call fails.
registry_models
¤
Registry data models.
This module contains Pydantic models for registry service data structures.
Classes:
-
ModuleStatusInfo–Module status response.
ModuleStatusInfo
¤
flowchart TD
digitalkin.services.registry.registry_models.ModuleStatusInfo[ModuleStatusInfo]
click digitalkin.services.registry.registry_models.ModuleStatusInfo href "" "digitalkin.services.registry.registry_models.ModuleStatusInfo"
Module status response.
registry_strategy
¤
Abstract base class for registry strategies.
Classes:
-
RegistryStrategy–Abstract base class for registry strategies.
RegistryStrategy
¤
RegistryStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, Any] | None = None,
)
flowchart TD
digitalkin.services.registry.registry_strategy.RegistryStrategy[RegistryStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.registry.registry_strategy.RegistryStrategy
click digitalkin.services.registry.registry_strategy.RegistryStrategy href "" "digitalkin.services.registry.registry_strategy.RegistryStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for registry strategies.
Defines the interface for registry operations including module discovery, registration, and status management.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
deregister–Deregister a module from the registry.
-
discover_by_id–Get module info by ID.
-
get_setup–Get setup info.
-
get_status–Get module status.
-
heartbeat–Send heartbeat to keep module active.
-
register–Register a module with the registry.
-
search–Search for modules by criteria.
-
wait_for_ready–Check if the registry backend is reachable.
deregister
abstractmethod
async
¤
discover_by_id
abstractmethod
async
¤
discover_by_id(module_id: str) -> ModuleInfo
Get module info by ID.
heartbeat
abstractmethod
async
¤
heartbeat(module_id: str) -> RegistryModuleStatus
Send heartbeat to keep module active.
Parameters:
Returns:
-
RegistryModuleStatus–Current module status after heartbeat.
Raises:
-
RegistryModuleNotFoundError–If module not found.
register
abstractmethod
async
¤
Register a module with the registry.
Note: The new proto only updates address/port/version for an existing module. The module must already exist in the registry database.
Parameters:
-
(module_id¤str) –Unique module identifier.
-
(address¤str) –Network address.
-
(port¤int) –Network port.
-
(version¤str) –Module version.
Returns:
-
ModuleInfo | None–ModuleInfo if successful, None otherwise.
search
abstractmethod
async
¤
search(
name: str | None = None,
module_type: str | None = None,
organization_id: str | None = None,
) -> list[ModuleInfo]
Search for modules by criteria.
Parameters:
-
(name¤str | None, default:None) –Filter by name (partial match via query).
-
(module_type¤str | None, default:None) –Filter by type (archetype, tool).
-
(organization_id¤str | None, default:None) –Filter by organization.
Returns:
-
list[ModuleInfo]–List of matching modules.
services_config
¤
Service Provider definitions.
Classes:
-
ServicesConfig–Service class describing the available services in a Module.
ServicesConfig
¤
ServicesConfig(
services_config_strategies: dict[str, ServicesStrategy | None] = {},
services_config_params: dict[str, dict[str, Any | None] | None] = {},
mode: ServicesMode = LOCAL,
**kwargs: dict[str, Any],
)
flowchart TD
digitalkin.services.services_config.ServicesConfig[ServicesConfig]
click digitalkin.services.services_config.ServicesConfig href "" "digitalkin.services.services_config.ServicesConfig"
Service class describing the available services in a Module.
This class manages the strategy implementations for various services, allowing them to be switched between local and remote modes.
Parameters:
-
(services_config_strategies¤dict[str, ServicesStrategy | None], default:{}) –Dictionary mapping service names to strategy implementations
-
(services_config_params¤dict[str, dict[str, Any | None] | None], default:{}) –Dictionary mapping service names to configuration parameters
-
(mode¤ServicesMode, default:LOCAL) –The mode of the services (local or remote)
-
(**kwargs¤dict[str, Any], default:{}) –Additional keyword arguments passed to the parent class constructor
Methods:
-
get_strategy_config–Get the configuration for a specific strategy.
-
init_strategy–Initialize a specific strategy.
-
update_mode–Update the strategy mode.
-
valid_strategy_names–Get the list of valid strategy names.
Attributes:
-
agent(type[AgentStrategy]) –Get the agent service strategy class based on the current mode.
-
communication(type[CommunicationStrategy]) –Get the communication service strategy class based on the current mode.
-
cost(type[CostStrategy]) –Get the cost service strategy class based on the current mode.
-
filesystem(type[FilesystemStrategy]) –Get the filesystem service strategy class based on the current mode.
-
identity(type[IdentityStrategy]) –Get the identity service strategy class based on the current mode.
-
registry(type[RegistryStrategy]) –Get the registry service strategy class based on the current mode.
-
snapshot(type[SnapshotStrategy]) –Get the snapshot service strategy class based on the current mode.
-
storage(type[StorageStrategy]) –Get the storage service strategy class based on the current mode.
-
task_manager(type[TaskManagerStrategy]) –Get the task_manager service strategy class based on the current mode.
-
user_profile(type[UserProfileStrategy]) –Get the user_profile service strategy class based on the current mode.
agent
property
¤
agent: type[AgentStrategy]
Get the agent service strategy class based on the current mode.
communication
property
¤
communication: type[CommunicationStrategy]
Get the communication service strategy class based on the current mode.
cost
property
¤
cost: type[CostStrategy]
Get the cost service strategy class based on the current mode.
filesystem
property
¤
filesystem: type[FilesystemStrategy]
Get the filesystem service strategy class based on the current mode.
identity
property
¤
identity: type[IdentityStrategy]
Get the identity service strategy class based on the current mode.
registry
property
¤
registry: type[RegistryStrategy]
Get the registry service strategy class based on the current mode.
snapshot
property
¤
snapshot: type[SnapshotStrategy]
Get the snapshot service strategy class based on the current mode.
storage
property
¤
storage: type[StorageStrategy]
Get the storage service strategy class based on the current mode.
task_manager
property
¤
task_manager: type[TaskManagerStrategy]
Get the task_manager service strategy class based on the current mode.
user_profile
property
¤
user_profile: type[UserProfileStrategy]
Get the user_profile service strategy class based on the current mode.
get_strategy_config
¤
init_strategy
¤
init_strategy(name: str, mission_id: str, setup_id: str, setup_version_id: str) -> Any
Initialize a specific strategy.
Parameters:
-
(name¤str) –The name of the strategy to initialize
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The setup ID for the strategy
-
(setup_version_id¤str) –The setup version ID for the strategy
Returns:
-
Any–The initialized strategy instance
Raises:
-
ValueError–If the strategy is not found
update_mode
¤
update_mode(mode: ServicesMode) -> None
Update the strategy mode.
Parameters:
-
(mode¤ServicesMode) –The new mode to use for all strategies
services_models
¤
This module contains the strategy models for the services.
Classes:
-
ServicesMode–Mode for strategy execution.
-
ServicesStrategy–Service class describing the available services in a Module with local and remote attributes.
ServicesMode
¤
flowchart TD
digitalkin.services.services_models.ServicesMode[ServicesMode]
click digitalkin.services.services_models.ServicesMode href "" "digitalkin.services.services_models.ServicesMode"
Mode for strategy execution.
ServicesStrategy
¤
flowchart TD
digitalkin.services.services_models.ServicesStrategy[ServicesStrategy]
click digitalkin.services.services_models.ServicesStrategy href "" "digitalkin.services.services_models.ServicesStrategy"
Service class describing the available services in a Module with local and remote attributes.
Attributes:
Methods:
-
__getitem__–Get the service strategy based on the mode.
setup
¤
This module is responsible for handling the setup service.
Modules:
-
default_setup–This module contains the abstract base class for setup strategies.
-
grpc_setup–Digital Kin Setup Service gRPC Client.
-
setup_strategy–This module contains the abstract base class for setup strategies.
default_setup
¤
This module contains the abstract base class for setup strategies.
Classes:
-
DefaultSetup–Abstract base class for setup strategies.
DefaultSetup
¤
DefaultSetup()
flowchart TD
digitalkin.services.setup.default_setup.DefaultSetup[DefaultSetup]
digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]
digitalkin.services.setup.setup_strategy.SetupStrategy --> digitalkin.services.setup.default_setup.DefaultSetup
click digitalkin.services.setup.default_setup.DefaultSetup href "" "digitalkin.services.setup.default_setup.DefaultSetup"
click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
Abstract base class for setup strategies.
Methods:
-
__post_init__–Lifecycle hook for post-initialization. Subclasses override with specific params.
-
create_setup–Create a new setup with comprehensive validation.
-
create_setup_version–Create a new setup version.
-
delete_setup–Delete a setup by its unique identifier.
-
delete_setup_version–Delete a setup version by its unique identifier.
-
get_setup–Retrieve a setup by its unique identifier.
-
get_setup_version–Retrieve a setup version by its unique identifier.
-
list_setups–List setups with optional filtering and pagination.
-
search_setup_versions–Search for setup versions based on filters.
-
update_setup–Update an existing setup.
-
update_setup_version–Update an existing setup version.
__post_init__
¤
Lifecycle hook for post-initialization. Subclasses override with specific params.
get_setup_version
async
¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData
Retrieve a setup version by its unique identifier.
Parameters:
Returns:
-
SetupVersionData–Dict[str, Any]: Setup version details.
Raises:
-
SetupServiceError–setup_id does not exist.
list_setups
async
¤
search_setup_versions
async
¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]
Search for setup versions based on filters.
Parameters:
-
(setup_version_dict¤dict[str, Any]) –Dictionary with optional 'name' or 'query_versions' filters.
Returns:
-
list[SetupVersionData]–List[SetupVersionData]: A list of matching setup version details.
Raises:
-
SetupServiceError–setup_id does not exist.
grpc_setup
¤
Digital Kin Setup Service gRPC Client.
Classes:
-
GrpcSetup–gRPC client implementation for the Setup service.
GrpcSetup
¤
GrpcSetup()
flowchart TD
digitalkin.services.setup.grpc_setup.GrpcSetup[GrpcSetup]
digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.setup.setup_strategy.SetupStrategy --> digitalkin.services.setup.grpc_setup.GrpcSetup
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.setup.grpc_setup.GrpcSetup
click digitalkin.services.setup.grpc_setup.GrpcSetup href "" "digitalkin.services.setup.grpc_setup.GrpcSetup"
click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client implementation for the Setup service.
Communicates with the remote SetupService gRPC server to manage setup configurations and versions.
Methods:
-
__post_init__–Init the channel from a config file.
-
close–Release this instance's gRPC channel ref. Subclasses override to release extra resources.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
create_setup–Create a new setup with comprehensive validation.
-
create_setup_version–Create a new setup version.
-
delete_setup–Delete a setup by its unique identifier.
-
delete_setup_version–Delete a setup version by its unique identifier.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_setup–Retrieve a setup by its unique identifier.
-
get_setup_version–Retrieve a setup version by its unique identifier.
-
handle_grpc_errors–Context manager for consistent gRPC error handling with detailed logging.
-
list_setups–List setups with optional filtering and pagination.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
search_setup_versions–Search for setup versions based on filters.
-
update_setup–Update an existing setup.
-
update_setup_version–Update an existing setup version.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
__post_init__
¤
__post_init__(config: ClientConfig) -> None
Init the channel from a config file.
Need to be call if the user register a gRPC channel.
close
async
¤
close() -> None
Release this instance's gRPC channel ref. Subclasses override to release extra resources.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
create_setup
async
¤
create_setup(setup_dict: dict[str, Any]) -> str
Create a new setup with comprehensive validation.
Parameters:
Returns:
-
bool(str) –Success status of setup creation.
Raises:
-
ValidationError–If setup data is invalid.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
create_setup_version
async
¤
create_setup_version(setup_version_dict: dict[str, Any]) -> str
Create a new setup version.
Parameters:
Returns:
-
str(str) –version of setup version creation.
Raises:
-
ValidationError–If setup version data is invalid.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
delete_setup
async
¤
delete_setup(setup_dict: dict[str, Any]) -> bool
Delete a setup by its unique identifier.
Parameters:
Returns:
-
bool(bool) –Success status of deletion.
Raises:
-
ValidationError–If the setup setup_id is missing.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
delete_setup_version
async
¤
delete_setup_version(setup_version_dict: dict[str, Any]) -> bool
Delete a setup version by its unique identifier.
Parameters:
Returns:
-
bool(bool) –Success status of version deletion.
Raises:
-
ValidationError–If the setup version name is missing.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_setup
async
¤
get_setup(setup_dict: dict[str, Any]) -> SetupData
Retrieve a setup by its unique identifier.
Parameters:
Returns:
-
SetupData–dict[str, Any]: Setup details including optional setup version.
Raises:
-
ValidationError–If the setup name is missing.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
get_setup_version
async
¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData
Retrieve a setup version by its unique identifier.
Parameters:
Returns:
-
SetupVersionData–dict[str, Any]: Setup version details.
Raises:
-
ValidationError–If the setup version id is missing.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
handle_grpc_errors
async
¤
handle_grpc_errors(operation: str) -> AsyncGenerator[Any, Any]
Context manager for consistent gRPC error handling with detailed logging.
Parameters:
-
(operation¤str) –Description of the operation being performed (e.g., "Get Setup", "Create Setup Version").
Yields:
-
AsyncGenerator[Any, Any]–Allow error handling in context.
Raises:
-
ValueError–Pydantic model validation failed - input data is malformed.
-
ServerError–gRPC communication failed - remote service returned error or is unreachable.
-
SetupServiceError–Unexpected error during setup operation - includes connection/timeout issues.
list_setups
async
¤
List setups with optional filtering and pagination.
Parameters:
-
(list_dict¤dict[str, Any]) –Dictionary with optional filters: - organisation_id: Filter by organisation - owner_id: Filter by owner - limit: Maximum number of results - offset: Number of results to skip
Returns:
Raises:
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
search_setup_versions
async
¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]
Search for setup versions based on filters.
Parameters:
Returns:
-
list[SetupVersionData]–list[dict[str, Any]]: A list of matching setup version details.
Raises:
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
-
ValidationError–If both name and version are not provided.
update_setup
async
¤
update_setup(setup_dict: dict[str, Any]) -> bool
Update an existing setup.
Parameters:
Returns:
-
bool(bool) –Success status of the update operation.
Raises:
-
ValidationError–If setup data is invalid.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
update_setup_version
async
¤
update_setup_version(setup_version_dict: dict[str, Any]) -> bool
Update an existing setup version.
Parameters:
Returns:
-
bool(bool) –Success status of the update operation.
Raises:
-
ValidationError–If setup version data is invalid.
-
ServerError–If gRPC operation fails.
-
SetupServiceError–For any unexpected internal error.
setup_strategy
¤
This module contains the abstract base class for setup strategies.
Classes:
-
SetupData–Pydantic model for Setup data validation.
-
SetupServiceError–Base exception for Setup service errors.
-
SetupStrategy–Abstract base class for setup strategies.
-
SetupVersionData–Pydantic model for SetupVersion data validation.
SetupData
¤
flowchart TD
digitalkin.services.setup.setup_strategy.SetupData[SetupData]
click digitalkin.services.setup.setup_strategy.SetupData href "" "digitalkin.services.setup.setup_strategy.SetupData"
Pydantic model for Setup data validation.
SetupServiceError
¤
flowchart TD
digitalkin.services.setup.setup_strategy.SetupServiceError[SetupServiceError]
click digitalkin.services.setup.setup_strategy.SetupServiceError href "" "digitalkin.services.setup.setup_strategy.SetupServiceError"
Base exception for Setup service errors.
SetupStrategy
¤
SetupStrategy()
flowchart TD
digitalkin.services.setup.setup_strategy.SetupStrategy[SetupStrategy]
click digitalkin.services.setup.setup_strategy.SetupStrategy href "" "digitalkin.services.setup.setup_strategy.SetupStrategy"
Abstract base class for setup strategies.
Methods:
-
__post_init__–Lifecycle hook for post-initialization. Subclasses override with specific params.
-
create_setup–Create a new setup with comprehensive validation.
-
create_setup_version–Create a new setup version.
-
delete_setup–Delete a setup by its unique identifier.
-
delete_setup_version–Delete a setup version by its unique identifier.
-
get_setup–Retrieve a setup by its unique identifier.
-
get_setup_version–Retrieve a setup version by its unique identifier.
-
list_setups–List setups with optional filtering and pagination.
-
search_setup_versions–Search for setup versions based on filters.
-
update_setup–Update an existing setup.
-
update_setup_version–Update an existing setup version.
__post_init__
¤
Lifecycle hook for post-initialization. Subclasses override with specific params.
create_setup_version
abstractmethod
async
¤
create_setup_version(setup_version_dict: dict[str, Any]) -> str
delete_setup_version
abstractmethod
async
¤
delete_setup_version(setup_version_dict: dict[str, Any]) -> bool
get_setup_version
abstractmethod
async
¤
get_setup_version(setup_version_dict: dict[str, Any]) -> SetupVersionData
Retrieve a setup version by its unique identifier.
Parameters:
Returns:
-
SetupVersionData–Dict[str, Any]: Setup version details.
list_setups
abstractmethod
async
¤
search_setup_versions
abstractmethod
async
¤
search_setup_versions(setup_version_dict: dict[str, Any]) -> list[SetupVersionData]
SetupVersionData
¤
flowchart TD
digitalkin.services.setup.setup_strategy.SetupVersionData[SetupVersionData]
click digitalkin.services.setup.setup_strategy.SetupVersionData href "" "digitalkin.services.setup.setup_strategy.SetupVersionData"
Pydantic model for SetupVersion data validation.
snapshot
¤
This module is responsible for handling the snapshot service.
Modules:
-
default_snapshot–Default snapshot.
-
snapshot_strategy–This module contains the abstract base class for snapshot strategies.
Classes:
-
DefaultSnapshot–Default snapshot strategy.
-
SnapshotStrategy–Abstract base class for snapshot strategies.
DefaultSnapshot
¤
DefaultSnapshot(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.snapshot.DefaultSnapshot[DefaultSnapshot]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.snapshot.DefaultSnapshot
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
click digitalkin.services.snapshot.DefaultSnapshot href "" "digitalkin.services.snapshot.DefaultSnapshot"
click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default snapshot strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
SnapshotStrategy
¤
SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.snapshot.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.SnapshotStrategy
click digitalkin.services.snapshot.SnapshotStrategy href "" "digitalkin.services.snapshot.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for snapshot strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
create
abstractmethod
¤
Create a new snapshot in the file system.
default_snapshot
¤
Default snapshot.
Classes:
-
DefaultSnapshot–Default snapshot strategy.
DefaultSnapshot
¤
DefaultSnapshot(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.snapshot.default_snapshot.DefaultSnapshot[DefaultSnapshot]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy --> digitalkin.services.snapshot.default_snapshot.DefaultSnapshot
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
click digitalkin.services.snapshot.default_snapshot.DefaultSnapshot href "" "digitalkin.services.snapshot.default_snapshot.DefaultSnapshot"
click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default snapshot strategy.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
snapshot_strategy
¤
This module contains the abstract base class for snapshot strategies.
Classes:
-
SnapshotStrategy–Abstract base class for snapshot strategies.
SnapshotStrategy
¤
SnapshotStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy[SnapshotStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy
click digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy href "" "digitalkin.services.snapshot.snapshot_strategy.SnapshotStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for snapshot strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
create–Create a new snapshot in the file system.
-
delete–Delete snapshots from the file system.
-
get–Get snapshots from the file system.
-
get_all–Get all snapshots from the file system.
-
update–Update snapshots in the file system.
create
abstractmethod
¤
Create a new snapshot in the file system.
storage
¤
This module is responsible for handling the storage service.
Modules:
-
default_storage–This module implements the default storage strategy.
-
grpc_storage–This module implements the default storage strategy.
-
storage_strategy–This module contains the abstract base class for storage strategies.
Classes:
-
DefaultStorage–Persist records in a local JSON file for quick local development.
-
GrpcStorage–gRPC client implementation for the Storage service.
-
StorageStrategy–Define CRUD + list/remove-collection against a collection/record store.
DefaultStorage
¤
DefaultStorage(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
storage_file_path: str = "local_storage",
)
flowchart TD
digitalkin.services.storage.DefaultStorage[DefaultStorage]
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.DefaultStorage
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
click digitalkin.services.storage.DefaultStorage href "" "digitalkin.services.storage.DefaultStorage"
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Persist records in a local JSON file for quick local development.
a JSON object of
{ "
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
GrpcStorage
¤
GrpcStorage(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
client_config: ClientConfig,
)
flowchart TD
digitalkin.services.storage.GrpcStorage[GrpcStorage]
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.GrpcStorage
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.storage.GrpcStorage
click digitalkin.services.storage.GrpcStorage href "" "digitalkin.services.storage.GrpcStorage"
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client implementation for the Storage service.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
list–Get all records in a collection under the given scope.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
read–Get a record by key under the given scope.
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
release_cached_channel
async
classmethod
¤
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
StorageStrategy
¤
StorageStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
)
flowchart TD
digitalkin.services.storage.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.StorageStrategy
click digitalkin.services.storage.StorageStrategy href "" "digitalkin.services.storage.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Define CRUD + list/remove-collection against a collection/record store.
Records are scoped by a context string (the proto field), which is either
self.mission_id (mission scope, the default) or self.setup_version_id
(setup-version scope). Both attributes are expected to already contain the
full prefix (missions:<id> / setup_versions:<id>).
Public methods accept scope: Literal["mission", "setup"] (default
"mission"); internally we resolve it to the matching context string and
pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.
Parameters:
-
(mission_id¤str) –Already-prefixed mission context (
missions:<id>). -
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –Already-prefixed setup-version context (
setup_versions:<id>). -
(config¤dict[str, type[BaseModel]]) –A dictionary mapping names to Pydantic model classes
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
default_storage
¤
This module implements the default storage strategy.
Classes:
-
DefaultStorage–Persist records in a local JSON file for quick local development.
DefaultStorage
¤
DefaultStorage(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
storage_file_path: str = "local_storage",
)
flowchart TD
digitalkin.services.storage.default_storage.DefaultStorage[DefaultStorage]
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.default_storage.DefaultStorage
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
click digitalkin.services.storage.default_storage.DefaultStorage href "" "digitalkin.services.storage.default_storage.DefaultStorage"
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Persist records in a local JSON file for quick local development.
a JSON object of
{ "
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
grpc_storage
¤
This module implements the default storage strategy.
Classes:
-
GrpcStorage–gRPC client implementation for the Storage service.
GrpcStorage
¤
GrpcStorage(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
client_config: ClientConfig,
)
flowchart TD
digitalkin.services.storage.grpc_storage.GrpcStorage[GrpcStorage]
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.services.storage.storage_strategy.StorageStrategy --> digitalkin.services.storage.grpc_storage.GrpcStorage
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.storage.grpc_storage.GrpcStorage
click digitalkin.services.storage.grpc_storage.GrpcStorage href "" "digitalkin.services.storage.grpc_storage.GrpcStorage"
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
gRPC client implementation for the Storage service.
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
list–Get all records in a collection under the given scope.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
read–Get a record by key under the given scope.
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
release_cached_channel
async
classmethod
¤
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
storage_strategy
¤
This module contains the abstract base class for storage strategies.
Classes:
-
DataType–Enum defining the types of data that can be stored.
-
StorageRecord–A single record stored in a collection, with metadata.
-
StorageServiceError–Base exception for Setup service errors.
-
StorageStrategy–Define CRUD + list/remove-collection against a collection/record store.
DataType
¤
flowchart TD
digitalkin.services.storage.storage_strategy.DataType[DataType]
click digitalkin.services.storage.storage_strategy.DataType href "" "digitalkin.services.storage.storage_strategy.DataType"
Enum defining the types of data that can be stored.
StorageRecord
¤
flowchart TD
digitalkin.services.storage.storage_strategy.StorageRecord[StorageRecord]
click digitalkin.services.storage.storage_strategy.StorageRecord href "" "digitalkin.services.storage.storage_strategy.StorageRecord"
A single record stored in a collection, with metadata.
-
digitalkin-
TriggerHandler -
mixins -
modules -
services
-
StorageServiceError
¤
flowchart TD
digitalkin.services.storage.storage_strategy.StorageServiceError[StorageServiceError]
click digitalkin.services.storage.storage_strategy.StorageServiceError href "" "digitalkin.services.storage.storage_strategy.StorageServiceError"
Base exception for Setup service errors.
StorageStrategy
¤
StorageStrategy(
mission_id: str,
setup_id: str,
setup_version_id: str,
config: dict[str, type[BaseModel]],
)
flowchart TD
digitalkin.services.storage.storage_strategy.StorageStrategy[StorageStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.storage.storage_strategy.StorageStrategy
click digitalkin.services.storage.storage_strategy.StorageStrategy href "" "digitalkin.services.storage.storage_strategy.StorageStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Define CRUD + list/remove-collection against a collection/record store.
Records are scoped by a context string (the proto field), which is either
self.mission_id (mission scope, the default) or self.setup_version_id
(setup-version scope). Both attributes are expected to already contain the
full prefix (missions:<id> / setup_versions:<id>).
Public methods accept scope: Literal["mission", "setup"] (default
"mission"); internally we resolve it to the matching context string and
pass that to the abstract _store/_read/_update/_remove/_list/_remove_collection.
Parameters:
-
(mission_id¤str) –Already-prefixed mission context (
missions:<id>). -
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –Already-prefixed setup-version context (
setup_versions:<id>). -
(config¤dict[str, type[BaseModel]]) –A dictionary mapping names to Pydantic model classes
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
list–Get all records in a collection under the given scope.
-
read–Get a record by key under the given scope.
-
remove–Delete a record from the storage under the given scope.
-
remove_collection–Wipe a collection clean under the given scope.
-
store–Store a new record in the storage.
-
update–Validate & overwrite an existing record under the given scope.
-
upsert–Insert or update a record atomically under the given scope.
list
async
¤
list(collection: str, scope: Scope = 'mission') -> list[StorageRecord]
Get all records in a collection under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(scope¤Scope, default:'mission') –Which context to list (default: "mission").
Returns:
-
list[StorageRecord]–A list of storage records under the resolved context.
read
async
¤
read(collection: str, record_id: str, scope: Scope = 'mission') -> StorageRecord | None
Get a record by key under the given scope.
Parameters:
-
(collection¤str) –The unique name to retrieve data for
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context to read from (default: "mission").
Returns:
-
StorageRecord | None–The matching record if it exists, otherwise None.
remove
async
¤
Delete a record from the storage under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
bool–True if the deletion was successful, False otherwise
remove_collection
async
¤
remove_collection(collection: str, scope: Scope = 'mission') -> bool
store
async
¤
store(
collection: str,
record_id: str | None,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Store a new record in the storage.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str | None) –The unique ID for the record (optional)
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –"mission" (default) writes under the current mission context; "setup" writes under the setup-version context.
Returns:
-
StorageRecord–The ID of the created record
Raises:
-
ValueError–If the data type is invalid or if validation fails
update
async
¤
update(
collection: str, record_id: str, data: dict[str, Any], scope: Scope = "mission"
) -> StorageRecord | None
Validate & overwrite an existing record under the given scope.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID of the record
-
(data¤dict[str, Any]) –The new data to store
-
(scope¤Scope, default:'mission') –Which context the record lives under (default: "mission").
Returns:
-
StorageRecord(StorageRecord | None) –The modified record
upsert
async
¤
upsert(
collection: str,
record_id: str,
data: dict[str, Any],
data_type: Literal["OUTPUT", "VIEW", "LOGS", "OTHER"] = "OUTPUT",
scope: Scope = "mission",
) -> StorageRecord
Insert or update a record atomically under the given scope.
If a record with the given collection/record_id exists under that context it is updated; otherwise a new record is created. The operation is protected by a per-record lock to prevent races.
Parameters:
-
(collection¤str) –The unique name for the record type
-
(record_id¤str) –The unique ID for the record
-
(data¤dict[str, Any]) –The data to store
-
(data_type¤Literal['OUTPUT', 'VIEW', 'LOGS', 'OTHER'], default:'OUTPUT') –The type of data being stored (default: OUTPUT)
-
(scope¤Scope, default:'mission') –Which context to upsert under (default: "mission").
Returns:
-
StorageRecord–The created or updated storage record
Raises:
-
ValueError–If the data type is invalid or if validation fails
-
StorageServiceError–If update of an existing record fails unexpectedly
task_manager
¤
Task manager signal service.
Modules:
-
default_task_manager–In-memory implementation of TaskManagerStrategy.
-
grpc_task_manager–gRPC implementation of TaskManagerStrategy using TaskManagerService.
-
task_manager_strategy–Abstract interface for task manager signal management.
Classes:
-
DefaultTaskManager–In-memory task signal service for single-process deployments.
-
TaskManagerStrategy–Abstract strategy for task manager signal management.
DefaultTaskManager
¤
DefaultTaskManager(
mission_id: str = "", setup_id: str = "", setup_version_id: str = ""
)
flowchart TD
digitalkin.services.task_manager.DefaultTaskManager[DefaultTaskManager]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.DefaultTaskManager
click digitalkin.services.task_manager.DefaultTaskManager href "" "digitalkin.services.task_manager.DefaultTaskManager"
click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
In-memory task signal service for single-process deployments.
Parameters:
-
(mission_id¤str, default:'') –Mission identifier (unused, required by init_strategy convention).
-
(setup_id¤str, default:'') –Setup identifier (unused, required by init_strategy convention).
-
(setup_version_id¤str, default:'') –Setup version identifier (unused, required by init_strategy convention).
Methods:
-
close–Poison all subscribers and clear state.
-
send_signal–Create or update a signal record and broadcast to subscribers.
-
subscribe_signals–Subscribe to signal updates via an in-memory queue.
-
unsubscribe_signals–Unsubscribe by sending a poison pill and removing the subscriber.
TaskManagerStrategy
¤
flowchart TD
digitalkin.services.task_manager.TaskManagerStrategy[TaskManagerStrategy]
click digitalkin.services.task_manager.TaskManagerStrategy href "" "digitalkin.services.task_manager.TaskManagerStrategy"
Abstract strategy for task manager signal management.
Defines the contract for upsert, subscribe, unsubscribe, and close operations used by TaskSession, TaskExecutor, and BaseTaskManager.
Methods:
-
close–Close the signal service and release resources.
-
send_signal–Create or update a signal record for a task.
-
subscribe_signals–Subscribe to signal updates for a specific task.
-
unsubscribe_signals–Unsubscribe from signal updates.
default_task_manager
¤
In-memory implementation of TaskManagerStrategy.
Classes:
-
DefaultTaskManager–In-memory task signal service for single-process deployments.
DefaultTaskManager
¤
DefaultTaskManager(
mission_id: str = "", setup_id: str = "", setup_version_id: str = ""
)
flowchart TD
digitalkin.services.task_manager.default_task_manager.DefaultTaskManager[DefaultTaskManager]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.default_task_manager.DefaultTaskManager
click digitalkin.services.task_manager.default_task_manager.DefaultTaskManager href "" "digitalkin.services.task_manager.default_task_manager.DefaultTaskManager"
click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
In-memory task signal service for single-process deployments.
Parameters:
-
(mission_id¤str, default:'') –Mission identifier (unused, required by init_strategy convention).
-
(setup_id¤str, default:'') –Setup identifier (unused, required by init_strategy convention).
-
(setup_version_id¤str, default:'') –Setup version identifier (unused, required by init_strategy convention).
Methods:
-
close–Poison all subscribers and clear state.
-
send_signal–Create or update a signal record and broadcast to subscribers.
-
subscribe_signals–Subscribe to signal updates via an in-memory queue.
-
unsubscribe_signals–Unsubscribe by sending a poison pill and removing the subscriber.
grpc_task_manager
¤
gRPC implementation of TaskManagerStrategy using TaskManagerService.
Classes:
-
GrpcTaskManager–gRPC-backed task signal service using TaskManagerService.
GrpcTaskManager
¤
GrpcTaskManager(
mission_id: str,
setup_id: str,
setup_version_id: str,
client_config: ClientConfig,
*,
poll_interval: float = float(get("DIGITALKIN_SIGNAL_POLL_INTERVAL", "1.0")),
initial_poll_interval: float = float(
get("DIGITALKIN_SIGNAL_INITIAL_POLL_INTERVAL", "0.1")
),
)
flowchart TD
digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager[GrpcTaskManager]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager
click digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager href "" "digitalkin.services.task_manager.grpc_task_manager.GrpcTaskManager"
click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC-backed task signal service using TaskManagerService.
Signal polling is delegated to a shared _SharedPoller per gRPC address, so N concurrent tasks share one controlled polling loop instead of N independent loops hammering the TaskManagerService.
Parameters:
-
(mission_id¤str) –Mission identifier (unused, required by init_strategy convention).
-
(setup_id¤str) –Setup identifier (unused, required by init_strategy convention).
-
(setup_version_id¤str) –Setup version identifier (unused, required by init_strategy convention).
-
(client_config¤ClientConfig) –gRPC client configuration.
-
(poll_interval¤float, default:float(get('DIGITALKIN_SIGNAL_POLL_INTERVAL', '1.0'))) –Maximum seconds between GetSignals polls.
-
(initial_poll_interval¤float, default:float(get('DIGITALKIN_SIGNAL_INITIAL_POLL_INTERVAL', '0.1'))) –Starting poll interval before exponential ramp-up.
Raises:
-
ImportError–If agentic_mesh_protocol.task_manager.v1 is not installed.
Methods:
-
close–Stop all subscriptions, flush pending signals, and close the gRPC channel.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
send_signal–Enqueue a signal for batched delivery via gRPC SendSignals.
-
subscribe_signals–Subscribe to signal updates via the shared poller.
-
unsubscribe_signals–Stop the subscription and wake its consumer via the shared poller.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close
async
¤
close() -> None
Stop all subscriptions, flush pending signals, and close the gRPC channel.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
send_signal
async
¤
Enqueue a signal for batched delivery via gRPC SendSignals.
Signals are accumulated in a shared per-channel send buffer and flushed in a single SendSignalsRequest either when the batch hits 50 items or after 100 ms — whichever comes first.
Parameters:
Returns:
Raises:
-
TaskManagerServiceError–If the gRPC call fails or the server rejects the request.
subscribe_signals
async
¤
Subscribe to signal updates via the shared poller.
Instead of an independent polling loop, this registers the task_id with the shared _SharedPoller and yields signals from a queue.
Parameters:
Returns:
unsubscribe_signals
async
¤
task_manager_strategy
¤
Abstract interface for task manager signal management.
Classes:
-
TaskManagerServiceError–Error raised by task manager service operations.
-
TaskManagerStrategy–Abstract strategy for task manager signal management.
TaskManagerServiceError
¤
flowchart TD
digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError[TaskManagerServiceError]
click digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerServiceError"
Error raised by task manager service operations.
TaskManagerStrategy
¤
flowchart TD
digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy[TaskManagerStrategy]
click digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy href "" "digitalkin.services.task_manager.task_manager_strategy.TaskManagerStrategy"
Abstract strategy for task manager signal management.
Defines the contract for upsert, subscribe, unsubscribe, and close operations used by TaskSession, TaskExecutor, and BaseTaskManager.
Methods:
-
close–Close the signal service and release resources.
-
send_signal–Create or update a signal record for a task.
-
subscribe_signals–Subscribe to signal updates for a specific task.
-
unsubscribe_signals–Unsubscribe from signal updates.
user_profile
¤
UserProfile service package.
Modules:
-
default_user_profile–Default user profile implementation.
-
grpc_user_profile–Digital Kin UserProfile Service gRPC Client.
-
user_profile_strategy–This module contains the abstract base class for UserProfile strategies.
Classes:
-
DefaultUserProfile–Default user profile strategy with in-memory storage.
-
GrpcUserProfile–gRPC client implementation for the UserProfile service.
-
UserProfileServiceError–Base exception for UserProfile service errors.
-
UserProfileStrategy–Abstract base class for UserProfile strategies.
DefaultUserProfile
¤
DefaultUserProfile(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.user_profile.DefaultUserProfile[DefaultUserProfile]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.DefaultUserProfile
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
click digitalkin.services.user_profile.DefaultUserProfile href "" "digitalkin.services.user_profile.DefaultUserProfile"
click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default user profile strategy with in-memory storage.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version
Methods:
-
add_user_profile–Add a user profile to the in-memory database (helper for testing).
-
close–Release resources held by this strategy. No-op by default.
-
get_user_profile–Get user profile from in-memory storage.
add_user_profile
¤
add_user_profile(user_profile_data: dict[str, Any]) -> None
GrpcUserProfile
¤
GrpcUserProfile(
mission_id: str, setup_id: str, setup_version_id: str, client_config: ClientConfig
)
flowchart TD
digitalkin.services.user_profile.GrpcUserProfile[GrpcUserProfile]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.GrpcUserProfile
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.user_profile.GrpcUserProfile
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.user_profile.GrpcUserProfile
click digitalkin.services.user_profile.GrpcUserProfile href "" "digitalkin.services.user_profile.GrpcUserProfile"
click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the UserProfile service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version
-
(client_config¤ClientConfig) –Client configuration for gRPC connection
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_user_profile–Get user profile by mission_id (which maps to user_id).
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_user_profile
async
¤
Get user profile by mission_id (which maps to user_id).
Returns:
Raises:
-
UserProfileServiceError–If the gRPC operation fails.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
UserProfileServiceError
¤
flowchart TD
digitalkin.services.user_profile.UserProfileServiceError[UserProfileServiceError]
click digitalkin.services.user_profile.UserProfileServiceError href "" "digitalkin.services.user_profile.UserProfileServiceError"
Base exception for UserProfile service errors.
UserProfileStrategy
¤
UserProfileStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.user_profile.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.UserProfileStrategy
click digitalkin.services.user_profile.UserProfileStrategy href "" "digitalkin.services.user_profile.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for UserProfile strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_user_profile–Get user profile data.
default_user_profile
¤
Default user profile implementation.
Classes:
-
DefaultUserProfile–Default user profile strategy with in-memory storage.
DefaultUserProfile
¤
DefaultUserProfile(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.user_profile.default_user_profile.DefaultUserProfile[DefaultUserProfile]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.default_user_profile.DefaultUserProfile
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
click digitalkin.services.user_profile.default_user_profile.DefaultUserProfile href "" "digitalkin.services.user_profile.default_user_profile.DefaultUserProfile"
click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Default user profile strategy with in-memory storage.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version
Methods:
-
add_user_profile–Add a user profile to the in-memory database (helper for testing).
-
close–Release resources held by this strategy. No-op by default.
-
get_user_profile–Get user profile from in-memory storage.
add_user_profile
¤
add_user_profile(user_profile_data: dict[str, Any]) -> None
grpc_user_profile
¤
Digital Kin UserProfile Service gRPC Client.
Classes:
-
GrpcUserProfile–gRPC client implementation for the UserProfile service.
GrpcUserProfile
¤
GrpcUserProfile(
mission_id: str, setup_id: str, setup_version_id: str, client_config: ClientConfig
)
flowchart TD
digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile[GrpcUserProfile]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper[GrpcClientWrapper]
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin[GrpcErrorHandlerMixin]
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin --> digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile
click digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile href "" "digitalkin.services.user_profile.grpc_user_profile.GrpcUserProfile"
click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
click digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper href "" "digitalkin.grpc_servers.utils.grpc_client_wrapper.GrpcClientWrapper"
click digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin href "" "digitalkin.grpc_servers.utils.grpc_error_handler.GrpcErrorHandlerMixin"
gRPC client implementation for the UserProfile service.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup
-
(setup_version_id¤str) –The ID of the setup version
-
(client_config¤ClientConfig) –Client configuration for gRPC connection
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
close_all_cached_channels–Close all cached channels and reset the cache.
-
close_channel–Release this instance's ref on the cached channel.
-
exec_grpc_query–Execute a gRPC query with from the query's rpc endpoint name.
-
get_user_profile–Get user profile by mission_id (which maps to user_id).
-
handle_grpc_errors–Handle gRPC errors for the given operation.
-
poll_grpc–Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
-
release_cached_channel–Decrement refcount for a cache key and close channel when last ref is released.
-
wait_for_ready–Check if the gRPC channel can connect within timeout.
close_all_cached_channels
async
classmethod
¤
close_all_cached_channels() -> None
Close all cached channels and reset the cache.
Intended for server shutdown to ensure clean resource release.
close_channel
async
¤
close_channel() -> None
Release this instance's ref on the cached channel.
The underlying channel is only closed when the last ref is released.
exec_grpc_query
async
¤
Execute a gRPC query with from the query's rpc endpoint name.
Retries on transient errors (UNAVAILABLE, INTERNAL, DEADLINE_EXCEEDED) with exponential backoff. Retry count and backoff base are configurable via DIGITALKIN_GRPC_QUERY_MAX_RETRIES and DIGITALKIN_GRPC_QUERY_BACKOFF_BASE_MS.
Parameters:
-
(query_endpoint¤str) –rpc query name (e.g., "GetSetup", "CreateSetupVersion")
-
(request¤Any) –gRPC protobuf request object
-
(timeout¤float | None, default:None) –Per-call timeout in seconds. Falls back to _QUERY_DEFAULT_TIMEOUT (env DIGITALKIN_GRPC_QUERY_TIMEOUT, default 30s) when None.
Returns:
-
Any–gRPC protobuf response object.
Raises:
-
ServerError–gRPC error with status code and details for caller to handle.
get_user_profile
async
¤
Get user profile by mission_id (which maps to user_id).
Returns:
Raises:
-
UserProfileServiceError–If the gRPC operation fails.
handle_grpc_errors
async
¤
handle_grpc_errors(
operation: str, service_error_class: type[Exception] | None = None
) -> AsyncGenerator[Any, Any]
Handle gRPC errors for the given operation.
Parameters:
-
(operation¤str) –Name of the operation being performed.
-
(service_error_class¤type[Exception] | None, default:None) –Optional specific service exception class to raise. If not provided, uses the generic ServerError.
Yields:
-
AsyncGenerator[Any, Any]–Context for the operation.
Raises:
-
ServerError–For gRPC-related errors.
-
service_error_class–For service-specific errors if provided.
poll_grpc
async
¤
Execute a single polling RPC. Returns None on DEADLINE_EXCEEDED (expected empty poll).
Unlike exec_grpc_query, DEADLINE_EXCEEDED is not an error for polling-style RPCs where the server holds the connection until a result is available or timeout occurs. No retry is performed — the caller is responsible for the retry loop.
Parameters:
-
(endpoint¤str) –RPC method name on self.stub.
-
(request¤Any) –gRPC request protobuf.
-
(timeout¤float) –Seconds before treating as 'no result available'.
Returns:
-
Any | None–gRPC response, or None if DEADLINE_EXCEEDED.
Raises:
-
ServerError–For any non-DEADLINE_EXCEEDED gRPC error.
release_cached_channel
async
classmethod
¤
user_profile_strategy
¤
This module contains the abstract base class for UserProfile strategies.
Classes:
-
UserProfileServiceError–Base exception for UserProfile service errors.
-
UserProfileStrategy–Abstract base class for UserProfile strategies.
UserProfileServiceError
¤
flowchart TD
digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError[UserProfileServiceError]
click digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileServiceError"
Base exception for UserProfile service errors.
UserProfileStrategy
¤
UserProfileStrategy(mission_id: str, setup_id: str, setup_version_id: str)
flowchart TD
digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy[UserProfileStrategy]
digitalkin.services.base_strategy.BaseStrategy[BaseStrategy]
digitalkin.services.base_strategy.BaseStrategy --> digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy
click digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy href "" "digitalkin.services.user_profile.user_profile_strategy.UserProfileStrategy"
click digitalkin.services.base_strategy.BaseStrategy href "" "digitalkin.services.base_strategy.BaseStrategy"
Abstract base class for UserProfile strategies.
Parameters:
-
(mission_id¤str) –The ID of the mission this strategy is associated with
-
(setup_id¤str) –The ID of the setup this strategy is associated with
-
(setup_version_id¤str) –The ID of the setup version this strategy is associated with
Methods:
-
close–Release resources held by this strategy. No-op by default.
-
get_user_profile–Get user profile data.
utils
¤
General utils folder.
Modules:
-
arg_parser–ArgParser and Action classes to ease command lines arguments settings.
-
conditional_schema–Conditional field visibility for react-jsonschema-form.
-
development_mode_action–ArgParser and Action classes to ease command lines arguments settings.
-
dynamic_schema–Dynamic schema utilities for runtime value refresh in Pydantic models.
-
llm_ready_schema–LLM format schema for Pydantic models.
-
package_discover–Secure module discovery and import utility for trigger handlers.
-
proto_utils–Protobuf conversion utilities.
-
schema_splitter–Schema splitter for react-jsonschema-form.
Classes:
-
ConditionalField–Metadata for conditional field visibility.
-
ConditionalSchemaMixin–Mixin for automatic conditional field processing in JSON schema.
-
DynamicField–Metadata class for Annotated fields with dynamic fetchers.
-
ResolveResult–Result of resolving dynamic fetchers.
Functions:
-
get_conditional_metadata–Extract ConditionalField from field metadata.
-
get_dynamic_metadata–Extract DynamicField metadata from a FieldInfo's metadata list.
-
get_fetchers–Extract fetchers from a field's DynamicField metadata.
-
has_conditional–Check if field has ConditionalField metadata.
-
has_dynamic–Check if a field has DynamicField metadata.
-
resolve–Resolve all dynamic fetchers to their actual values in parallel.
-
resolve_safe–Resolve fetchers with structured error handling.
ConditionalField
dataclass
¤
ConditionalField(
trigger: str, show_when: bool | str | list[str], required_when_shown: bool = True
)
Metadata for conditional field visibility.
Use with typing.Annotated to mark fields that should only appear when a trigger field has a specific value.
Parameters:
-
(trigger¤str) –Name of the field that controls visibility.
-
(show_when¤bool | str | list[str]) –Value(s) that trigger field must have to show this field. Can be a boolean, string, or list of strings for multiple values.
-
(required_when_shown¤bool, default:True) –Whether field is required when visible. Defaults to True.
Example
Boolean condition¤
web_search_engine: Annotated[ str, Conditional(trigger="web_search_enabled", show_when=True), ] = Field(...)
Enum condition¤
advanced_option: Annotated[ str, Conditional(trigger="mode", show_when="advanced"), ] = Field(...)
Multiple values condition¤
shared_feature: Annotated[ bool, Conditional(trigger="mode", show_when=["standard", "advanced"]), ] = Field(...)
Methods:
-
__post_init__–Normalize single-item lists to scalar values.
ConditionalSchemaMixin
¤
flowchart TD
digitalkin.utils.ConditionalSchemaMixin[ConditionalSchemaMixin]
click digitalkin.utils.ConditionalSchemaMixin href "" "digitalkin.utils.ConditionalSchemaMixin"
Mixin for automatic conditional field processing in JSON schema.
Inherit from this mixin to automatically generate JSON Schema with if/then clauses for fields marked with ConditionalField metadata.
The mixin processes Annotated fields with Conditional metadata and: 1. Removes conditional fields from main properties 2. Adds them to allOf with if/then clauses 3. Groups multiple fields with the same condition together
Example
class Config(ConditionalSchemaMixin, BaseModel): mode: Literal["basic", "advanced"] = Field(...)
advanced_option: Annotated[
str,
Conditional(trigger="mode", show_when="advanced"),
] = Field(...)
Generates schema with:¤
{¤
"properties": {"mode": {...}},¤
"allOf": [{¤
"if": {"properties": {"mode": {"const": "advanced"}}},¤
"then": {"properties": {"advanced_option": {...}}}¤
}]¤
}¤
Methods:
-
__get_pydantic_json_schema__–Generate JSON schema with conditional field handling.
__get_pydantic_json_schema__
classmethod
¤
__get_pydantic_json_schema__(
core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue
DynamicField
¤
Metadata class for Annotated fields with dynamic fetchers.
Use with typing.Annotated to mark fields that need runtime value resolution. Fetchers are callables (sync or async) that return values at runtime.
Parameters:
-
(**fetchers¤Fetcher[Any], default:{}) –Mapping of key names to fetcher callables. Each fetcher is a function (sync or async) that takes no arguments and returns the value for that key (e.g., enum values, defaults).
Example
from typing import Annotated
async def fetch_models() -> list[str]: return await api.get_models()
class Setup(SetupModel): model: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")
Methods:
ResolveResult
dataclass
¤
Result of resolving dynamic fetchers.
Provides structured access to resolved values and any errors that occurred. This allows callers to handle partial failures gracefully.
Attributes:
-
values(dict[str, Any]) –Dict mapping key names to successfully resolved values.
-
errors(dict[str, Exception]) –Dict mapping key names to exceptions that occurred during resolution.
Methods:
-
get–Get a resolved value by key.
get_conditional_metadata
¤
get_conditional_metadata(field_info: FieldInfo) -> ConditionalField | None
Extract ConditionalField from field metadata.
Parameters:
-
(field_info¤FieldInfo) –The Pydantic FieldInfo object to inspect.
Returns:
-
ConditionalField | None–The ConditionalField metadata instance if found, None otherwise.
get_dynamic_metadata
¤
get_dynamic_metadata(field_info: FieldInfo) -> DynamicField | None
Extract DynamicField metadata from a FieldInfo's metadata list.
Parameters:
-
(field_info¤FieldInfo) –The Pydantic FieldInfo object to inspect.
Returns:
-
DynamicField | None–The DynamicField metadata instance if found, None otherwise.
get_fetchers
¤
get_fetchers(field_info: FieldInfo) -> dict[str, Fetcher[Any]]
has_conditional
¤
has_conditional(field_info: FieldInfo) -> bool
has_dynamic
¤
has_dynamic(field_info: FieldInfo) -> bool
resolve
async
¤
resolve(
fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> dict[str, Any]
Resolve all dynamic fetchers to their actual values in parallel.
Fetchers are executed concurrently using asyncio.gather() for better performance when multiple async fetchers are involved.
Parameters:
-
(fetchers¤dict[str, Fetcher[Any]]) –Dict mapping key names to fetcher callables.
-
(timeout¤float | None, default:DEFAULT_TIMEOUT) –Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied.
Returns:
Raises:
-
TimeoutError–If timeout is exceeded.
-
Exception–If any fetcher raises an exception, it is propagated.
Example
fetchers = {"enum": fetch_models, "default": get_default} resolved = await resolve(fetchers, timeout=5.0)
resolved =¤
resolve_safe
async
¤
resolve_safe(
fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> ResolveResult
Resolve fetchers with structured error handling.
Unlike resolve(), this function catches individual fetcher errors
and returns them in a structured result, allowing partial success.
Parameters:
-
(fetchers¤dict[str, Fetcher[Any]]) –Dict mapping key names to fetcher callables.
-
(timeout¤float | None, default:DEFAULT_TIMEOUT) –Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied. Note: timeout applies to the entire operation, not individual fetchers.
Returns:
-
ResolveResult–ResolveResult with values and any errors that occurred.
Example
result = await resolve_safe(fetchers, timeout=5.0) if result.success: print("All resolved:", result.values) elif result.partial: print("Partial success:", result.values) print("Errors:", result.errors) else: print("All failed:", result.errors)
arg_parser
¤
ArgParser and Action classes to ease command lines arguments settings.
Classes:
-
ArgParser–ArgParse Abstract class to join all argparse argument in the same parser.
ArgParser
¤
ArgParser(prog: str = 'PROG')
ArgParse Abstract class to join all argparse argument in the same parser.
Custom help display to allow multiple parser and subparser help message.
Examples:¤
Inherit this class in your base class. Override '_add_parser_args', '_add_exclusive_args' and '_add_subparser_args'.
class WindowHandler(ArgParser):
@staticmethod
def _add_screen_parser_args(parser) -> None:
parser.add_argument(
"-f", "--fps", type=int, default=60, help="Screen FPS", dest="fps"
)
def _add_media_parser_args(self, parser) -> None:
parser.add_argument(
"-w",
"--workers",
type=int,
default=3,
help="Number of worker processing media in background",
dest="media_worker_count"
)
def _add_parser_args(self, parser) -> None:
super()._add_parser_args(parser)
self._add_screen_parser_args(parser)
self._add_media_parser_args(parser)
def __init__(self):
# init the parser
super().__init__()
Classes:
-
HelpAction–Custom HelpAction to display subparsers helps too.
Attributes:
HelpAction
¤
flowchart TD
digitalkin.utils.arg_parser.ArgParser.HelpAction[HelpAction]
click digitalkin.utils.arg_parser.ArgParser.HelpAction href "" "digitalkin.utils.arg_parser.ArgParser.HelpAction"
Custom HelpAction to display subparsers helps too.
Methods:
-
__call__–Override the HelpActions as it doesn't handle subparser well.
conditional_schema
¤
Conditional field visibility for react-jsonschema-form.
This module provides a clean way to mark fields as conditional using Annotated metadata, generating JSON Schema with if/then clauses for react-jsonschema-form.
Example
from typing import Annotated, Literal from pydantic import BaseModel, Field from digitalkin.utils import Conditional, ConditionalSchemaMixin
class Tools(ConditionalSchemaMixin, BaseModel): web_search_enabled: bool = Field(...)
web_search_engine: Annotated[
Literal["duckduckgo", "tavily"],
Conditional(trigger="web_search_enabled", show_when=True),
] = Field(...)
See Also
- Documentation: docs/api/conditional_schema.md
- Tests: tests/utils/test_conditional_schema.py
Classes:
-
ConditionalField–Metadata for conditional field visibility.
-
ConditionalSchemaMixin–Mixin for automatic conditional field processing in JSON schema.
Functions:
-
get_conditional_metadata–Extract ConditionalField from field metadata.
-
has_conditional–Check if field has ConditionalField metadata.
ConditionalField
dataclass
¤
ConditionalField(
trigger: str, show_when: bool | str | list[str], required_when_shown: bool = True
)
Metadata for conditional field visibility.
Use with typing.Annotated to mark fields that should only appear when a trigger field has a specific value.
Parameters:
-
(trigger¤str) –Name of the field that controls visibility.
-
(show_when¤bool | str | list[str]) –Value(s) that trigger field must have to show this field. Can be a boolean, string, or list of strings for multiple values.
-
(required_when_shown¤bool, default:True) –Whether field is required when visible. Defaults to True.
Example
Boolean condition¤
web_search_engine: Annotated[ str, Conditional(trigger="web_search_enabled", show_when=True), ] = Field(...)
Enum condition¤
advanced_option: Annotated[ str, Conditional(trigger="mode", show_when="advanced"), ] = Field(...)
Multiple values condition¤
shared_feature: Annotated[ bool, Conditional(trigger="mode", show_when=["standard", "advanced"]), ] = Field(...)
Methods:
-
__post_init__–Normalize single-item lists to scalar values.
ConditionalSchemaMixin
¤
flowchart TD
digitalkin.utils.conditional_schema.ConditionalSchemaMixin[ConditionalSchemaMixin]
click digitalkin.utils.conditional_schema.ConditionalSchemaMixin href "" "digitalkin.utils.conditional_schema.ConditionalSchemaMixin"
Mixin for automatic conditional field processing in JSON schema.
Inherit from this mixin to automatically generate JSON Schema with if/then clauses for fields marked with ConditionalField metadata.
The mixin processes Annotated fields with Conditional metadata and: 1. Removes conditional fields from main properties 2. Adds them to allOf with if/then clauses 3. Groups multiple fields with the same condition together
Example
class Config(ConditionalSchemaMixin, BaseModel): mode: Literal["basic", "advanced"] = Field(...)
advanced_option: Annotated[
str,
Conditional(trigger="mode", show_when="advanced"),
] = Field(...)
Generates schema with:¤
{¤
"properties": {"mode": {...}},¤
"allOf": [{¤
"if": {"properties": {"mode": {"const": "advanced"}}},¤
"then": {"properties": {"advanced_option": {...}}}¤
}]¤
}¤
Methods:
-
__get_pydantic_json_schema__–Generate JSON schema with conditional field handling.
__get_pydantic_json_schema__
classmethod
¤
__get_pydantic_json_schema__(
core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue
get_conditional_metadata
¤
get_conditional_metadata(field_info: FieldInfo) -> ConditionalField | None
Extract ConditionalField from field metadata.
Parameters:
-
(field_info¤FieldInfo) –The Pydantic FieldInfo object to inspect.
Returns:
-
ConditionalField | None–The ConditionalField metadata instance if found, None otherwise.
has_conditional
¤
has_conditional(field_info: FieldInfo) -> bool
development_mode_action
¤
ArgParser and Action classes to ease command lines arguments settings.
Classes:
-
DevelopmentModeMappingAction–ArgParse Action to map an environment variable to a ServicesMode enum.
DevelopmentModeMappingAction
¤
DevelopmentModeMappingAction(
env_var: str, required: bool = True, default: str | None = None, **kwargs: Any
)
flowchart TD
digitalkin.utils.development_mode_action.DevelopmentModeMappingAction[DevelopmentModeMappingAction]
click digitalkin.utils.development_mode_action.DevelopmentModeMappingAction href "" "digitalkin.utils.development_mode_action.DevelopmentModeMappingAction"
ArgParse Action to map an environment variable to a ServicesMode enum.
Methods:
-
__call__–Set the attribute to the corresponding class.
dynamic_schema
¤
Dynamic schema utilities for runtime value refresh in Pydantic models.
This module provides a clean way to mark fields as dynamic using Annotated metadata, allowing their schema values to be refreshed at runtime via sync or async fetchers.
Example
from typing import Annotated from digitalkin.utils import DynamicField
class AgentSetup(SetupModel): model_name: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")
See Also
- Documentation: docs/api/dynamic_schema.md
- Tests: tests/utils/test_dynamic_schema.py
Classes:
-
DynamicField–Metadata class for Annotated fields with dynamic fetchers.
-
ResolveResult–Result of resolving dynamic fetchers.
Functions:
-
get_dynamic_metadata–Extract DynamicField metadata from a FieldInfo's metadata list.
-
get_fetchers–Extract fetchers from a field's DynamicField metadata.
-
has_dynamic–Check if a field has DynamicField metadata.
-
resolve–Resolve all dynamic fetchers to their actual values in parallel.
-
resolve_safe–Resolve fetchers with structured error handling.
DynamicField
¤
Metadata class for Annotated fields with dynamic fetchers.
Use with typing.Annotated to mark fields that need runtime value resolution. Fetchers are callables (sync or async) that return values at runtime.
Parameters:
-
(**fetchers¤Fetcher[Any], default:{}) –Mapping of key names to fetcher callables. Each fetcher is a function (sync or async) that takes no arguments and returns the value for that key (e.g., enum values, defaults).
Example
from typing import Annotated
async def fetch_models() -> list[str]: return await api.get_models()
class Setup(SetupModel): model: Annotated[str, DynamicField(enum=fetch_models)] = Field(default="gpt-4")
Methods:
ResolveResult
dataclass
¤
Result of resolving dynamic fetchers.
Provides structured access to resolved values and any errors that occurred. This allows callers to handle partial failures gracefully.
Attributes:
-
values(dict[str, Any]) –Dict mapping key names to successfully resolved values.
-
errors(dict[str, Exception]) –Dict mapping key names to exceptions that occurred during resolution.
Methods:
-
get–Get a resolved value by key.
get_dynamic_metadata
¤
get_dynamic_metadata(field_info: FieldInfo) -> DynamicField | None
Extract DynamicField metadata from a FieldInfo's metadata list.
Parameters:
-
(field_info¤FieldInfo) –The Pydantic FieldInfo object to inspect.
Returns:
-
DynamicField | None–The DynamicField metadata instance if found, None otherwise.
get_fetchers
¤
get_fetchers(field_info: FieldInfo) -> dict[str, Fetcher[Any]]
has_dynamic
¤
has_dynamic(field_info: FieldInfo) -> bool
resolve
async
¤
resolve(
fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> dict[str, Any]
Resolve all dynamic fetchers to their actual values in parallel.
Fetchers are executed concurrently using asyncio.gather() for better performance when multiple async fetchers are involved.
Parameters:
-
(fetchers¤dict[str, Fetcher[Any]]) –Dict mapping key names to fetcher callables.
-
(timeout¤float | None, default:DEFAULT_TIMEOUT) –Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied.
Returns:
Raises:
-
TimeoutError–If timeout is exceeded.
-
Exception–If any fetcher raises an exception, it is propagated.
Example
fetchers = {"enum": fetch_models, "default": get_default} resolved = await resolve(fetchers, timeout=5.0)
resolved =¤
resolve_safe
async
¤
resolve_safe(
fetchers: dict[str, Fetcher[Any]], *, timeout: float | None = DEFAULT_TIMEOUT
) -> ResolveResult
Resolve fetchers with structured error handling.
Unlike resolve(), this function catches individual fetcher errors
and returns them in a structured result, allowing partial success.
Parameters:
-
(fetchers¤dict[str, Fetcher[Any]]) –Dict mapping key names to fetcher callables.
-
(timeout¤float | None, default:DEFAULT_TIMEOUT) –Optional timeout in seconds for all fetchers combined. If None (default), no timeout is applied. Note: timeout applies to the entire operation, not individual fetchers.
Returns:
-
ResolveResult–ResolveResult with values and any errors that occurred.
Example
result = await resolve_safe(fetchers, timeout=5.0) if result.success: print("All resolved:", result.values) elif result.partial: print("Partial success:", result.values) print("Errors:", result.errors) else: print("All failed:", result.errors)
llm_ready_schema
¤
LLM format schema for Pydantic models.
This module provides functionality to generate JSON schemas for Pydantic models ready for LLMs.
Classes:
-
CustomOrderSchema–Custom schema generator to sort keys in a specific order.
Functions:
-
inline_refs–Recursively resolve and inline all $ref in the schema.
-
llm_ready_schema–Convert a Pydantic model to a JSON schema ready for LLMs.
CustomOrderSchema
¤
flowchart TD
digitalkin.utils.llm_ready_schema.CustomOrderSchema[CustomOrderSchema]
click digitalkin.utils.llm_ready_schema.CustomOrderSchema href "" "digitalkin.utils.llm_ready_schema.CustomOrderSchema"
Custom schema generator to sort keys in a specific order.
Methods:
-
sort–Sort the keys of the schema in a specific order.
sort
¤
sort(value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue
inline_refs
¤
package_discover
¤
Secure module discovery and import utility for trigger handlers.
Classes:
-
DiscoveryError–Raised when discovery fails due to invalid inputs.
-
ModuleDiscoverer–Encapsulates secure, structured discovery and import of trigger modules.
-
SecurityError–Raised when security constraints are violated.
DiscoveryError
¤
flowchart TD
digitalkin.utils.package_discover.DiscoveryError[DiscoveryError]
click digitalkin.utils.package_discover.DiscoveryError href "" "digitalkin.utils.package_discover.DiscoveryError"
Raised when discovery fails due to invalid inputs.
ModuleDiscoverer
¤
ModuleDiscoverer(
packages: list[str],
file_pattern: str = "*_trigger.py",
max_file_size: int = 1024 * 1024,
)
Encapsulates secure, structured discovery and import of trigger modules.
Attributes:
-
packages–List of Python package paths to scan.
-
file_pattern–Glob pattern to match module filenames.
-
safe_mode–If True, skips unsafe imports.
-
max_file_size–Maximum file size allowed for import (bytes).
Parameters:
-
(packages¤list[str]) –List of package names to scan.
-
(file_pattern¤str, default:'*_trigger.py') –Glob pattern for matching modules.
-
(max_file_size¤int, default:1024 * 1024) –Limit for module file sizes in bytes.
Methods:
-
__str__–Return a string representation of registered trigger handler classes.
-
discover_modules–Discover and import matching modules across configured packages.
-
get_registered_protocols_with_info–Get registered protocols with their descriptions.
-
get_trigger–Retrieve a trigger handler instance based on the provided protocol and input instance type.
-
init_handlers–Instantiate all registered trigger handler classes.
-
register_trigger–Register a trigger handler class for a specific protocol.
discover_modules
¤
Discover and import matching modules across configured packages.
Returns:
Raises:
-
DiscoveryError–If initial inputs are invalid.
get_registered_protocols_with_info
¤
get_registered_protocols_with_info(*, exclude_utility: bool = False) -> dict[str, str]
get_trigger
staticmethod
¤
get_trigger(
handlers: dict[str, tuple[TriggerHandler, ...]],
protocol: str,
input_instance: DataTrigger,
) -> TriggerHandler
Retrieve a trigger handler instance based on the provided protocol and input instance type.
Parameters:
-
(handlers¤dict[str, tuple[TriggerHandler, ...]]) –Mapping of protocol name to handler instance tuples.
-
(protocol¤str) –The protocol name (ignored internally,
input_instance.protocolis used instead). -
(input_instance¤DataTrigger) –The input trigger instance used to determine the correct handler.
Returns:
-
TriggerHandler(TriggerHandler) –An instance of the trigger handler matching the input format.
Raises:
-
ValueError–If no handler is registered for the specified protocol, or if no handler matches the type of the input instance.
init_handlers
¤
init_handlers(context: ModuleContext) -> dict[str, tuple[TriggerHandler, ...]]
Instantiate all registered trigger handler classes.
Parameters:
-
(context¤ModuleContext) –Module context to pass to each handler constructor.
Returns:
-
dict[str, tuple[TriggerHandler, ...]]–Mapping of protocol name to handler instance tuples.
register_trigger
¤
register_trigger(handler_cls: type[TriggerHandler]) -> type[TriggerHandler]
Register a trigger handler class for a specific protocol.
Parameters:
-
(handler_cls¤type[TriggerHandler]) –The trigger handler class to register.
Returns:
-
type[TriggerHandler]–The registered trigger handler class.
Raises:
-
ValueError–If a handler for the protocol is already registered.
SecurityError
¤
flowchart TD
digitalkin.utils.package_discover.SecurityError[SecurityError]
click digitalkin.utils.package_discover.SecurityError href "" "digitalkin.utils.package_discover.SecurityError"
Raised when security constraints are violated.
proto_utils
¤
Protobuf conversion utilities.
Functions:
-
proto_to_dict–Convert a protobuf message to a dict preserving snake_case field names.
proto_to_dict
¤
proto_to_dict(msg: Message, *, with_defaults: bool = False) -> dict
Convert a protobuf message to a dict preserving snake_case field names.
Parameters:
-
(msg¤Message) –Protobuf message to convert.
-
(with_defaults¤bool, default:False) –If True, include fields with default/zero values.
Returns:
-
dict–Dictionary representation with original field names preserved.
schema_splitter
¤
Schema splitter for react-jsonschema-form.
Classes:
-
SchemaSplitter–Splits a combined JSON schema into jsonschema and uischema for react-jsonschema-form.