digitalkin 0.2.25rc0__py3-none-any.whl → 0.3.2.dev14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. base_server/server_async_insecure.py +6 -5
  2. base_server/server_async_secure.py +6 -5
  3. base_server/server_sync_insecure.py +5 -4
  4. base_server/server_sync_secure.py +5 -4
  5. digitalkin/__version__.py +1 -1
  6. digitalkin/core/__init__.py +1 -0
  7. digitalkin/core/common/__init__.py +9 -0
  8. digitalkin/core/common/factories.py +156 -0
  9. digitalkin/core/job_manager/__init__.py +1 -0
  10. digitalkin/{modules → core}/job_manager/base_job_manager.py +138 -32
  11. digitalkin/core/job_manager/single_job_manager.py +373 -0
  12. digitalkin/{modules → core}/job_manager/taskiq_broker.py +121 -26
  13. digitalkin/core/job_manager/taskiq_job_manager.py +541 -0
  14. digitalkin/core/task_manager/__init__.py +1 -0
  15. digitalkin/core/task_manager/base_task_manager.py +539 -0
  16. digitalkin/core/task_manager/local_task_manager.py +108 -0
  17. digitalkin/core/task_manager/remote_task_manager.py +87 -0
  18. digitalkin/core/task_manager/surrealdb_repository.py +266 -0
  19. digitalkin/core/task_manager/task_executor.py +249 -0
  20. digitalkin/core/task_manager/task_session.py +368 -0
  21. digitalkin/grpc_servers/__init__.py +1 -19
  22. digitalkin/grpc_servers/_base_server.py +3 -3
  23. digitalkin/grpc_servers/module_server.py +120 -195
  24. digitalkin/grpc_servers/module_servicer.py +81 -44
  25. digitalkin/grpc_servers/utils/__init__.py +1 -0
  26. digitalkin/grpc_servers/utils/exceptions.py +0 -8
  27. digitalkin/grpc_servers/utils/grpc_client_wrapper.py +25 -9
  28. digitalkin/grpc_servers/utils/grpc_error_handler.py +53 -0
  29. digitalkin/grpc_servers/utils/utility_schema_extender.py +100 -0
  30. digitalkin/logger.py +64 -27
  31. digitalkin/mixins/__init__.py +19 -0
  32. digitalkin/mixins/base_mixin.py +10 -0
  33. digitalkin/mixins/callback_mixin.py +24 -0
  34. digitalkin/mixins/chat_history_mixin.py +110 -0
  35. digitalkin/mixins/cost_mixin.py +76 -0
  36. digitalkin/mixins/file_history_mixin.py +93 -0
  37. digitalkin/mixins/filesystem_mixin.py +46 -0
  38. digitalkin/mixins/logger_mixin.py +51 -0
  39. digitalkin/mixins/storage_mixin.py +79 -0
  40. digitalkin/models/__init__.py +1 -1
  41. digitalkin/models/core/__init__.py +1 -0
  42. digitalkin/{modules/job_manager → models/core}/job_manager_models.py +3 -11
  43. digitalkin/models/core/task_monitor.py +74 -0
  44. digitalkin/models/grpc_servers/__init__.py +1 -0
  45. digitalkin/{grpc_servers/utils → models/grpc_servers}/models.py +92 -7
  46. digitalkin/models/module/__init__.py +18 -11
  47. digitalkin/models/module/base_types.py +61 -0
  48. digitalkin/models/module/module.py +9 -1
  49. digitalkin/models/module/module_context.py +282 -6
  50. digitalkin/models/module/module_types.py +29 -105
  51. digitalkin/models/module/setup_types.py +490 -0
  52. digitalkin/models/module/tool_cache.py +68 -0
  53. digitalkin/models/module/tool_reference.py +117 -0
  54. digitalkin/models/module/utility.py +167 -0
  55. digitalkin/models/services/__init__.py +9 -0
  56. digitalkin/models/services/cost.py +1 -0
  57. digitalkin/models/services/registry.py +35 -0
  58. digitalkin/models/services/storage.py +39 -5
  59. digitalkin/modules/__init__.py +5 -1
  60. digitalkin/modules/_base_module.py +265 -167
  61. digitalkin/modules/archetype_module.py +6 -1
  62. digitalkin/modules/tool_module.py +16 -3
  63. digitalkin/modules/trigger_handler.py +7 -6
  64. digitalkin/modules/triggers/__init__.py +8 -0
  65. digitalkin/modules/triggers/healthcheck_ping_trigger.py +45 -0
  66. digitalkin/modules/triggers/healthcheck_services_trigger.py +63 -0
  67. digitalkin/modules/triggers/healthcheck_status_trigger.py +52 -0
  68. digitalkin/services/__init__.py +4 -0
  69. digitalkin/services/communication/__init__.py +7 -0
  70. digitalkin/services/communication/communication_strategy.py +76 -0
  71. digitalkin/services/communication/default_communication.py +101 -0
  72. digitalkin/services/communication/grpc_communication.py +234 -0
  73. digitalkin/services/cost/__init__.py +9 -2
  74. digitalkin/services/cost/grpc_cost.py +9 -42
  75. digitalkin/services/filesystem/default_filesystem.py +0 -2
  76. digitalkin/services/filesystem/grpc_filesystem.py +10 -39
  77. digitalkin/services/registry/__init__.py +22 -1
  78. digitalkin/services/registry/default_registry.py +135 -4
  79. digitalkin/services/registry/exceptions.py +47 -0
  80. digitalkin/services/registry/grpc_registry.py +306 -0
  81. digitalkin/services/registry/registry_models.py +15 -0
  82. digitalkin/services/registry/registry_strategy.py +88 -4
  83. digitalkin/services/services_config.py +25 -3
  84. digitalkin/services/services_models.py +5 -1
  85. digitalkin/services/setup/default_setup.py +6 -7
  86. digitalkin/services/setup/grpc_setup.py +52 -15
  87. digitalkin/services/storage/grpc_storage.py +4 -4
  88. digitalkin/services/user_profile/__init__.py +12 -0
  89. digitalkin/services/user_profile/default_user_profile.py +55 -0
  90. digitalkin/services/user_profile/grpc_user_profile.py +69 -0
  91. digitalkin/services/user_profile/user_profile_strategy.py +25 -0
  92. digitalkin/utils/__init__.py +28 -0
  93. digitalkin/utils/arg_parser.py +1 -1
  94. digitalkin/utils/development_mode_action.py +2 -2
  95. digitalkin/utils/dynamic_schema.py +483 -0
  96. digitalkin/utils/package_discover.py +1 -2
  97. digitalkin/utils/schema_splitter.py +207 -0
  98. {digitalkin-0.2.25rc0.dist-info → digitalkin-0.3.2.dev14.dist-info}/METADATA +11 -30
  99. digitalkin-0.3.2.dev14.dist-info/RECORD +143 -0
  100. {digitalkin-0.2.25rc0.dist-info → digitalkin-0.3.2.dev14.dist-info}/top_level.txt +1 -0
  101. modules/archetype_with_tools_module.py +244 -0
  102. modules/cpu_intensive_module.py +1 -1
  103. modules/dynamic_setup_module.py +338 -0
  104. modules/minimal_llm_module.py +1 -1
  105. modules/text_transform_module.py +1 -1
  106. monitoring/digitalkin_observability/__init__.py +46 -0
  107. monitoring/digitalkin_observability/http_server.py +150 -0
  108. monitoring/digitalkin_observability/interceptors.py +176 -0
  109. monitoring/digitalkin_observability/metrics.py +201 -0
  110. monitoring/digitalkin_observability/prometheus.py +137 -0
  111. monitoring/tests/test_metrics.py +172 -0
  112. services/filesystem_module.py +7 -5
  113. services/storage_module.py +4 -2
  114. digitalkin/grpc_servers/registry_server.py +0 -65
  115. digitalkin/grpc_servers/registry_servicer.py +0 -456
  116. digitalkin/grpc_servers/utils/factory.py +0 -180
  117. digitalkin/modules/job_manager/single_job_manager.py +0 -294
  118. digitalkin/modules/job_manager/taskiq_job_manager.py +0 -290
  119. digitalkin-0.2.25rc0.dist-info/RECORD +0 -89
  120. /digitalkin/{grpc_servers/utils → models/grpc_servers}/types.py +0 -0
  121. {digitalkin-0.2.25rc0.dist-info → digitalkin-0.3.2.dev14.dist-info}/WHEEL +0 -0
  122. {digitalkin-0.2.25rc0.dist-info → digitalkin-0.3.2.dev14.dist-info}/licenses/LICENSE +0 -0
@@ -1,24 +1,300 @@
1
1
  """Define the module context used in the triggers."""
2
2
 
3
+ import os
4
+ from collections.abc import AsyncGenerator, Callable, Coroutine
5
+ from datetime import tzinfo
3
6
  from types import SimpleNamespace
7
+ from typing import Any
8
+ from zoneinfo import ZoneInfo
4
9
 
10
+ from digitalkin.logger import logger
11
+ from digitalkin.models.module.tool_cache import ToolCache
12
+ from digitalkin.services.agent.agent_strategy import AgentStrategy
13
+ from digitalkin.services.communication.communication_strategy import CommunicationStrategy
5
14
  from digitalkin.services.cost.cost_strategy import CostStrategy
6
15
  from digitalkin.services.filesystem.filesystem_strategy import FilesystemStrategy
16
+ from digitalkin.services.identity.identity_strategy import IdentityStrategy
17
+ from digitalkin.services.registry.registry_strategy import RegistryStrategy
18
+ from digitalkin.services.snapshot.snapshot_strategy import SnapshotStrategy
7
19
  from digitalkin.services.storage.storage_strategy import StorageStrategy
20
+ from digitalkin.services.user_profile.user_profile_strategy import UserProfileStrategy
8
21
 
9
22
 
10
- class ModuleContext(SimpleNamespace):
11
- """ModuleContext provides a container for strategies and resources used by a module.
23
+ class Session(SimpleNamespace):
24
+ """Session data container with mandatory setup_id and mission_id."""
25
+
26
+ job_id: str
27
+ mission_id: str
28
+ setup_id: str
29
+ setup_version_id: str
30
+ timezone: tzinfo
31
+
32
+ def __init__(
33
+ self,
34
+ job_id: str,
35
+ mission_id: str,
36
+ setup_id: str,
37
+ setup_version_id: str,
38
+ timezone: tzinfo | None = None,
39
+ **kwargs: dict[str, Any],
40
+ ) -> None:
41
+ """Init Module Session.
42
+
43
+ Raises:
44
+ ValueError: If mandatory args are missing.
45
+ """
46
+ if not setup_id:
47
+ msg = "setup_id is mandatory"
48
+ raise ValueError(msg)
49
+ if not setup_version_id:
50
+ msg = "setup_version_id is mandatory"
51
+ raise ValueError(msg)
52
+ if not mission_id:
53
+ msg = "mission_id is mandatory"
54
+ raise ValueError(msg)
55
+ if not job_id:
56
+ msg = "job_id is mandatory"
57
+ raise ValueError(msg)
58
+
59
+ self.job_id = job_id
60
+ self.mission_id = mission_id
61
+ self.setup_id = setup_id
62
+ self.setup_version_id = setup_version_id
63
+ self.timezone = timezone or ZoneInfo(os.environ.get("DIGITALKIN_TIMEZONE", "Europe/Paris"))
12
64
 
13
- Attributes:
14
- cost (CostStrategy): The strategy used to calculate or manage costs within the module.
15
- filesystem (FilesystemStrategy): The strategy for interacting with the filesystem.
16
- storage (StorageStrategy): The strategy for handling storage operations.
65
+ super().__init__(**kwargs)
66
+
67
+ def current_ids(self) -> dict[str, str]:
68
+ """Return current session ids as a dictionary.
69
+
70
+ Returns:
71
+ A dictionary containing the current session ids.
72
+ """
73
+ return {
74
+ "job_id": self.job_id,
75
+ "mission_id": self.mission_id,
76
+ "setup_id": self.setup_id,
77
+ "setup_version_id": self.setup_version_id,
78
+ }
79
+
80
+
81
+ class ModuleContext:
82
+ """ModuleContext provides a container for strategies and resources used by a module.
17
83
 
18
84
  This context object is designed to be passed to module components, providing them with
19
85
  access to shared strategies and resources. Additional attributes may be set dynamically.
20
86
  """
21
87
 
88
+ # services list
89
+ agent: AgentStrategy
90
+ communication: CommunicationStrategy
22
91
  cost: CostStrategy
23
92
  filesystem: FilesystemStrategy
93
+ identity: IdentityStrategy
94
+ registry: RegistryStrategy
95
+ snapshot: SnapshotStrategy
24
96
  storage: StorageStrategy
97
+ user_profile: UserProfileStrategy
98
+
99
+ session: Session
100
+ callbacks: SimpleNamespace
101
+ metadata: SimpleNamespace
102
+ helpers: SimpleNamespace
103
+ state: SimpleNamespace = SimpleNamespace()
104
+ tool_cache: ToolCache
105
+
106
+ def __init__( # noqa: PLR0913, PLR0917
107
+ self,
108
+ agent: AgentStrategy,
109
+ communication: CommunicationStrategy,
110
+ cost: CostStrategy,
111
+ filesystem: FilesystemStrategy,
112
+ identity: IdentityStrategy,
113
+ registry: RegistryStrategy,
114
+ snapshot: SnapshotStrategy,
115
+ storage: StorageStrategy,
116
+ user_profile: UserProfileStrategy,
117
+ session: dict[str, Any],
118
+ metadata: dict[str, Any] = {},
119
+ helpers: dict[str, Any] = {},
120
+ callbacks: dict[str, Any] = {},
121
+ tool_cache: ToolCache | None = None,
122
+ ) -> None:
123
+ """Register mandatory services, session, metadata and callbacks.
124
+
125
+ Args:
126
+ agent: AgentStrategy.
127
+ communication: CommunicationStrategy.
128
+ cost: CostStrategy.
129
+ filesystem: FilesystemStrategy.
130
+ identity: IdentityStrategy.
131
+ registry: RegistryStrategy.
132
+ snapshot: SnapshotStrategy.
133
+ storage: StorageStrategy.
134
+ user_profile: UserProfileStrategy.
135
+ metadata: dict defining differents Module metadata.
136
+ helpers: dict different user defined helpers.
137
+ session: dict referring the session IDs or informations.
138
+ callbacks: Functions allowing user to agent interaction.
139
+ tool_cache: ToolCache with pre-resolved tool references from setup.
140
+ """
141
+ self.agent = agent
142
+ self.communication = communication
143
+ self.cost = cost
144
+ self.filesystem = filesystem
145
+ self.identity = identity
146
+ self.registry = registry
147
+ self.snapshot = snapshot
148
+ self.storage = storage
149
+ self.user_profile = user_profile
150
+
151
+ self.metadata = SimpleNamespace(**metadata)
152
+ self.session = Session(**session)
153
+ self.helpers = SimpleNamespace(**helpers)
154
+ self.callbacks = SimpleNamespace(**callbacks)
155
+ self.tool_cache = tool_cache or ToolCache()
156
+
157
+ async def call_module_by_id(
158
+ self,
159
+ module_id: str,
160
+ input_data: dict,
161
+ setup_id: str,
162
+ mission_id: str,
163
+ callback: Callable[[dict], Coroutine[Any, Any, None]] | None = None,
164
+ ) -> AsyncGenerator[dict, None]:
165
+ """Call a module by ID, discovering address/port from registry.
166
+
167
+ Args:
168
+ module_id: Module identifier to look up in registry.
169
+ input_data: Input data as dictionary.
170
+ setup_id: Setup configuration ID.
171
+ mission_id: Mission context ID.
172
+ callback: Optional callback for each response.
173
+
174
+ Yields:
175
+ Streaming responses from module as dictionaries.
176
+ """
177
+ module_info = self.registry.discover_by_id(module_id)
178
+
179
+ logger.debug(
180
+ "Calling module by ID",
181
+ extra={
182
+ "module_id": module_id,
183
+ "address": module_info.address,
184
+ "port": module_info.port,
185
+ },
186
+ )
187
+
188
+ async for response in self.communication.call_module(
189
+ module_address=module_info.address,
190
+ module_port=module_info.port,
191
+ input_data=input_data,
192
+ setup_id=setup_id,
193
+ mission_id=mission_id,
194
+ callback=callback,
195
+ ):
196
+ yield response
197
+
198
+ async def get_module_schemas_by_id(
199
+ self,
200
+ module_id: str,
201
+ *,
202
+ llm_format: bool = False,
203
+ ) -> dict[str, dict]:
204
+ """Get module schemas by ID, discovering address/port from registry.
205
+
206
+ Args:
207
+ module_id: Module identifier to look up in registry.
208
+ llm_format: If True, return LLM-optimized schema format.
209
+
210
+ Returns:
211
+ Dictionary containing schemas: {"input": ..., "output": ..., "setup": ..., "secret": ...}
212
+ """
213
+ module_info = self.registry.discover_by_id(module_id)
214
+
215
+ logger.debug(
216
+ "Getting module schemas by ID",
217
+ extra={
218
+ "module_id": module_id,
219
+ "address": module_info.address,
220
+ "port": module_info.port,
221
+ },
222
+ )
223
+
224
+ return await self.communication.get_module_schemas(
225
+ module_address=module_info.address,
226
+ module_port=module_info.port,
227
+ llm_format=llm_format,
228
+ )
229
+
230
+ async def create_openai_style_tool(self, tool_name: str) -> dict[str, Any] | None:
231
+ """Create OpenAI-style function calling schema for a tool.
232
+
233
+ Uses tool cache (fast path) with registry fallback. Fetches the tool's
234
+ input schema and wraps it in OpenAI function calling format.
235
+
236
+ Args:
237
+ tool_name: Module ID to look up (checks cache first, then registry).
238
+
239
+ Returns:
240
+ OpenAI-style tool schema if found, None otherwise.
241
+ """
242
+ module_info = self.tool_cache.get(tool_name, registry=self.registry)
243
+ if not module_info:
244
+ return None
245
+
246
+ schemas = await self.communication.get_module_schemas(
247
+ module_address=module_info.address,
248
+ module_port=module_info.port,
249
+ llm_format=True,
250
+ )
251
+
252
+ return {
253
+ "type": "function",
254
+ "function": {
255
+ "module_id": module_info.module_id,
256
+ "name": module_info.name or "undefined",
257
+ "description": module_info.documentation or "",
258
+ "parameters": schemas["input"],
259
+ },
260
+ }
261
+
262
+ def create_tool_function(
263
+ self,
264
+ module_id: str,
265
+ ) -> Callable[..., AsyncGenerator[dict, None]] | None:
266
+ """Create async generator function for a tool.
267
+
268
+ Returns an async generator that calls the remote tool module via gRPC
269
+ and yields each response as it arrives until end_of_stream or gRPC ends.
270
+
271
+ Args:
272
+ module_id: Module ID to look up (checks cache first, then registry).
273
+
274
+ Returns:
275
+ Async generator function if tool found, None otherwise.
276
+ """
277
+ module_info = self.tool_cache.get(module_id, registry=self.registry)
278
+ if not module_info:
279
+ return None
280
+
281
+ communication = self.communication
282
+ session = self.session
283
+ address = module_info.address
284
+ port = module_info.port
285
+
286
+ async def tool_function(**kwargs: Any) -> AsyncGenerator[dict, None]: # noqa: ANN401
287
+ wrapped_input = {"root": kwargs}
288
+ async for response in communication.call_module(
289
+ module_address=address,
290
+ module_port=port,
291
+ input_data=wrapped_input,
292
+ setup_id=session.setup_id,
293
+ mission_id=session.mission_id,
294
+ ):
295
+ yield response
296
+
297
+ tool_function.__name__ = module_info.name or module_info.module_id
298
+ tool_function.__doc__ = module_info.documentation or ""
299
+
300
+ return tool_function
@@ -1,105 +1,29 @@
1
- """Types for module models."""
2
-
3
- from datetime import datetime, timezone
4
- from typing import Any, ClassVar, Generic, TypeVar, cast
5
-
6
- from pydantic import BaseModel, ConfigDict, Field, create_model
7
-
8
- from digitalkin.logger import logger
9
-
10
-
11
- class DataTrigger(BaseModel):
12
- """Defines the root input model exposing the protocol.
13
-
14
- The mandatory protocol is important to define the module beahvior following the user or agent input.
15
-
16
- Example:
17
- class MyInput(DataModel):
18
- root: DataTrigger
19
- user_define_data: Any
20
-
21
- # Usage
22
- my_input = MyInput(root=DataTrigger(protocol="message"))
23
- print(my_input.root.protocol) # Output: message
24
- """
25
-
26
- protocol: ClassVar[str]
27
- created_at: str = datetime.now(tz=timezone.utc).isoformat()
28
-
29
-
30
- DataTriggerT = TypeVar("DataTriggerT", bound=DataTrigger)
31
-
32
-
33
- class DataModel(BaseModel, Generic[DataTriggerT]):
34
- """Base definition of input model showing mandatory root fields.
35
-
36
- The Model define the Module Input, usually referring to multiple input type defined by an union.
37
-
38
- Example:
39
- class ModuleInput(DataModel):
40
- root: FileInput | MessageInput
41
- """
42
-
43
- root: DataTriggerT
44
- annotations: dict[str, str] = Field(
45
- default={},
46
- title="Annotations",
47
- description="Additional metadata or annotations related to the output. ex {'role': 'user'}",
48
- )
49
-
50
-
51
- InputModelT = TypeVar("InputModelT", bound=DataModel)
52
- OutputModelT = TypeVar("OutputModelT", bound=DataModel)
53
- SecretModelT = TypeVar("SecretModelT", bound=BaseModel)
54
- SetupModelT = TypeVar("SetupModelT", bound="SetupModel")
55
-
56
-
57
- class SetupModel(BaseModel):
58
- """Base definition of setup model showing mandatory root fields.
59
-
60
- Optionally, the setup model can define a config option in json_schema_extra to be used to initialize the Kin.
61
-
62
- Example:
63
- class MySetup(SetupModel):
64
- name: str = Field()
65
- number: int = Field(..., json_schema_extra={"config": True})
66
- """
67
-
68
- @classmethod
69
- def get_clean_model(cls, *, config_fields: bool, hidden_fields: bool) -> type[SetupModelT]: # type: ignore
70
- """Dynamically builds and returns a new BaseModel subclass.
71
-
72
- containing only those fields where json_schema_extra["config"] == True.
73
-
74
- Returns:
75
- Type[BaseModel]: A new BaseModel subclass with the filtered fields.
76
-
77
- Raises:
78
- ValueError: If both config_fields and hidden_fields are set to True.
79
- """
80
- clean_fields: dict[str, Any] = {}
81
- for name, field_info in cls.model_fields.items():
82
- extra = getattr(field_info, "json_schema_extra", {}) or {}
83
- is_config = bool(extra.get("config", False))
84
- is_hidden = bool(extra.get("hidden", False))
85
-
86
- # Skip config unless explicitly included
87
- if is_config and not config_fields:
88
- logger.debug("Skipping '%s' (config-only)", name)
89
- continue
90
-
91
- # Skip hidden unless explicitly included
92
- if is_hidden and not hidden_fields:
93
- logger.debug("Skipping '%s' (hidden-only)", name)
94
- continue
95
-
96
- clean_fields[name] = (field_info.annotation, field_info)
97
-
98
- # Dynamically create a model e.g. "SetupModel"
99
- m = create_model(
100
- f"{cls.__name__}",
101
- __base__=BaseModel,
102
- __config__=ConfigDict(arbitrary_types_allowed=True),
103
- **clean_fields,
104
- )
105
- return cast("type[SetupModelT]", m)
1
+ """Types for module models - backward compatibility re-exports.
2
+
3
+ This module re-exports types from their new locations for backward compatibility.
4
+ New code should import directly from the specific modules:
5
+ - digitalkin.models.module.base_types for DataTrigger, DataModel, TypeVars
6
+ - digitalkin.models.module.setup_types for SetupModel
7
+ """
8
+
9
+ from digitalkin.models.module.base_types import (
10
+ DataModel,
11
+ DataTrigger,
12
+ DataTriggerT,
13
+ InputModelT,
14
+ OutputModelT,
15
+ SecretModelT,
16
+ SetupModelT,
17
+ )
18
+ from digitalkin.models.module.setup_types import SetupModel
19
+
20
+ __all__ = [
21
+ "DataModel",
22
+ "DataTrigger",
23
+ "DataTriggerT",
24
+ "InputModelT",
25
+ "OutputModelT",
26
+ "SecretModelT",
27
+ "SetupModel",
28
+ "SetupModelT",
29
+ ]