sapiopycommons 2025.9.5rc727__py3-none-any.whl → 2025.9.8a728__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.

Potentially problematic release.


This version of sapiopycommons might be problematic. Click here for more details.

Files changed (52) hide show
  1. sapiopycommons/ai/converter_service_base.py +132 -0
  2. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2.py +43 -0
  3. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2.pyi +31 -0
  4. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2_grpc.py +24 -0
  5. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2.py +123 -0
  6. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2.pyi +598 -0
  7. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2_grpc.py +24 -0
  8. sapiopycommons/ai/protoapi/plan/converter/converter_pb2.py +51 -0
  9. sapiopycommons/ai/protoapi/plan/converter/converter_pb2.pyi +63 -0
  10. sapiopycommons/ai/protoapi/plan/converter/converter_pb2_grpc.py +149 -0
  11. sapiopycommons/ai/protoapi/plan/item/item_container_pb2.py +55 -0
  12. sapiopycommons/ai/protoapi/plan/item/item_container_pb2.pyi +90 -0
  13. sapiopycommons/ai/protoapi/plan/item/item_container_pb2_grpc.py +24 -0
  14. sapiopycommons/ai/protoapi/plan/script/script_pb2.py +59 -0
  15. sapiopycommons/ai/protoapi/plan/script/script_pb2.pyi +102 -0
  16. sapiopycommons/ai/protoapi/plan/script/script_pb2_grpc.py +153 -0
  17. sapiopycommons/ai/protoapi/plan/step_output_pb2.py +45 -0
  18. sapiopycommons/ai/protoapi/plan/step_output_pb2.pyi +42 -0
  19. sapiopycommons/ai/protoapi/plan/step_output_pb2_grpc.py +24 -0
  20. sapiopycommons/ai/protoapi/plan/step_pb2.py +43 -0
  21. sapiopycommons/ai/protoapi/plan/step_pb2.pyi +43 -0
  22. sapiopycommons/ai/protoapi/plan/step_pb2_grpc.py +24 -0
  23. sapiopycommons/ai/protoapi/plan/tool/entry_pb2.py +41 -0
  24. sapiopycommons/ai/protoapi/plan/tool/entry_pb2.pyi +35 -0
  25. sapiopycommons/ai/protoapi/plan/tool/entry_pb2_grpc.py +24 -0
  26. sapiopycommons/ai/protoapi/plan/tool/tool_pb2.py +75 -0
  27. sapiopycommons/ai/protoapi/plan/tool/tool_pb2.pyi +237 -0
  28. sapiopycommons/ai/protoapi/plan/tool/tool_pb2_grpc.py +154 -0
  29. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2.py +39 -0
  30. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2.pyi +32 -0
  31. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2_grpc.py +24 -0
  32. sapiopycommons/ai/protobuf_utils.py +504 -0
  33. sapiopycommons/ai/server.py +106 -0
  34. sapiopycommons/ai/test_client.py +356 -0
  35. sapiopycommons/ai/tool_service_base.py +961 -0
  36. sapiopycommons/callbacks/callback_util.py +16 -26
  37. sapiopycommons/eln/experiment_handler.py +5 -12
  38. sapiopycommons/files/temp_files.py +49 -0
  39. sapiopycommons/flowcyto/flow_cyto.py +24 -2
  40. sapiopycommons/general/accession_service.py +28 -2
  41. sapiopycommons/multimodal/multimodal.py +24 -2
  42. sapiopycommons/recordmodel/record_handler.py +0 -4
  43. sapiopycommons/rules/eln_rule_handler.py +0 -3
  44. sapiopycommons/rules/on_save_rule_handler.py +0 -3
  45. sapiopycommons/webhook/webservice_handlers.py +1 -1
  46. {sapiopycommons-2025.9.5rc727.dist-info → sapiopycommons-2025.9.8a728.dist-info}/METADATA +2 -2
  47. {sapiopycommons-2025.9.5rc727.dist-info → sapiopycommons-2025.9.8a728.dist-info}/RECORD +49 -16
  48. sapiopycommons/ai/tool_of_tools.py +0 -917
  49. sapiopycommons/files/assay_plate_reader.py +0 -93
  50. sapiopycommons/files/file_text_converter.py +0 -207
  51. {sapiopycommons-2025.9.5rc727.dist-info → sapiopycommons-2025.9.8a728.dist-info}/WHEEL +0 -0
  52. {sapiopycommons-2025.9.5rc727.dist-info → sapiopycommons-2025.9.8a728.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,961 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ import json
6
+ import logging
7
+ import re
8
+ import traceback
9
+ from abc import abstractmethod, ABC
10
+ from logging import Logger
11
+ from typing import Any, Iterable, Sequence, Mapping
12
+
13
+ from grpc import ServicerContext
14
+ from sapiopylib.rest.User import SapioUser, ensure_logger_initialized
15
+ from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition
16
+
17
+ from sapiopycommons.ai.protoapi.fielddefinitions.fields_pb2 import FieldValueMapPbo, FieldValuePbo
18
+ from sapiopycommons.ai.protoapi.fielddefinitions.velox_field_def_pb2 import VeloxFieldDefPbo, FieldTypePbo, \
19
+ SelectionPropertiesPbo, IntegerPropertiesPbo, DoublePropertiesPbo, BooleanPropertiesPbo, StringPropertiesPbo
20
+ from sapiopycommons.ai.protoapi.plan.item.item_container_pb2 import ContentTypePbo
21
+ from sapiopycommons.ai.protoapi.plan.tool.entry_pb2 import StepOutputBatchPbo, StepItemContainerPbo, \
22
+ StepBinaryContainerPbo, StepCsvContainerPbo, StepCsvHeaderRowPbo, StepCsvRowPbo, StepJsonContainerPbo, \
23
+ StepTextContainerPbo, StepInputBatchPbo
24
+ from sapiopycommons.ai.protoapi.plan.tool.tool_pb2 import ToolDetailsRequestPbo, ToolDetailsResponsePbo, \
25
+ ToolDetailsPbo, ProcessStepRequestPbo, ProcessStepResponsePbo, ToolOutputDetailsPbo, ToolIoConfigBasePbo, \
26
+ ToolInputDetailsPbo, ExampleContainerPbo, ProcessStepResponseStatusPbo
27
+ from sapiopycommons.ai.protoapi.plan.tool.tool_pb2_grpc import ToolServiceServicer
28
+ from sapiopycommons.ai.protoapi.session.sapio_conn_info_pb2 import SapioUserSecretTypePbo, SapioConnectionInfoPbo
29
+ from sapiopycommons.ai.protobuf_utils import ProtobufUtils
30
+ from sapiopycommons.ai.test_client import ContainerType
31
+ from sapiopycommons.files.file_util import FileUtil
32
+ from sapiopycommons.files.temp_files import TempFileHandler
33
+ from sapiopycommons.general.aliases import FieldMap, FieldValue
34
+
35
+
36
+ # FR-47422: Created classes.
37
+ class SapioToolResult(ABC):
38
+ """
39
+ A class representing a result from a Sapio tool. Instantiate one of the subclasses to create a result object.
40
+ """
41
+
42
+ @abstractmethod
43
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
44
+ """
45
+ Convert this SapioToolResult object to a StepOutputBatchPbo or list of FieldValueMapPbo proto objects.
46
+ """
47
+ pass
48
+
49
+
50
+ class BinaryResult(SapioToolResult):
51
+ """
52
+ A class representing binary results from a Sapio tool.
53
+ """
54
+ binary_data: list[bytes]
55
+ content_type: str
56
+ file_extensions: list[str]
57
+ name: str
58
+
59
+ def __init__(self, binary_data: list[bytes], content_type: str = "binary", file_extensions: list[str] = None,
60
+ name: str | None = None):
61
+ """
62
+ :param binary_data: The binary data as a list of bytes.
63
+ :param content_type: The content type of the data.
64
+ :param file_extensions: A list of file extensions that this binary data can be saved as.
65
+ :param name: An optional identifying name for this result that will be accessible to the next tool.
66
+ """
67
+ self.binary_data = binary_data
68
+ self.content_type = content_type
69
+ self.file_extensions = file_extensions if file_extensions else []
70
+ self.name = name
71
+
72
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
73
+ return StepOutputBatchPbo(
74
+ item_container=StepItemContainerPbo(
75
+ content_type=ContentTypePbo(name=self.content_type, extensions=self.file_extensions),
76
+ container_name=self.name,
77
+ binary_container=StepBinaryContainerPbo(items=self.binary_data)
78
+ )
79
+ )
80
+
81
+
82
+ class CsvResult(SapioToolResult):
83
+ """
84
+ A class representing CSV results from a Sapio tool.
85
+ """
86
+ csv_data: list[dict[str, Any]]
87
+ content_type: str
88
+ file_extensions: list[str]
89
+ name: str
90
+
91
+ def __init__(self, csv_data: list[dict[str, Any]], content_type: str = "csv", file_extensions: list[str] = None,
92
+ name: str | None = None):
93
+ """
94
+ :param csv_data: The list of CSV data results, provided as a list of dictionaries of column name to value.
95
+ :param content_type: The content type of the data.
96
+ :param file_extensions: A list of file extensions that this binary data can be saved as.
97
+ :param name: An optional identifying name for this result that will be accessible to the next tool.
98
+ """
99
+ self.csv_data = csv_data
100
+ self.content_type = content_type
101
+ self.file_extensions = file_extensions if file_extensions else ["csv"]
102
+ self.name = name
103
+
104
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
105
+ return StepOutputBatchPbo(
106
+ item_container=StepItemContainerPbo(
107
+ content_type=ContentTypePbo(name=self.content_type, extensions=self.file_extensions),
108
+ container_name=self.name,
109
+ csv_container=StepCsvContainerPbo(
110
+ header=StepCsvHeaderRowPbo(cells=self.csv_data[0].keys()),
111
+ items=[StepCsvRowPbo(cells=[str(x) for x in row.values()]) for row in self.csv_data]
112
+ )
113
+ ) if self.csv_data else None
114
+ )
115
+
116
+
117
+ class FieldMapResult(SapioToolResult):
118
+ """
119
+ A class representing field map results from a Sapio tool.
120
+ """
121
+ field_maps: list[FieldMap]
122
+
123
+ def __init__(self, field_maps: list[FieldMap]):
124
+ """
125
+ :param field_maps: A list of field maps, where each map is a dictionary of field names to values. Each entry
126
+ will create a new data record in the system, so long as the tool definition specifies an output data type
127
+ name.
128
+ """
129
+ self.field_maps = field_maps
130
+
131
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
132
+ new_records: list[FieldValueMapPbo] = []
133
+ for field_map in self.field_maps:
134
+ fields: dict[str, FieldValuePbo] = {}
135
+ for field, value in field_map.items():
136
+ field_value = FieldValuePbo()
137
+ if isinstance(value, str):
138
+ field_value.string_value = value
139
+ elif isinstance(value, int):
140
+ field_value.int_value = value
141
+ elif isinstance(value, float):
142
+ field_value.double_value = value
143
+ elif isinstance(value, bool):
144
+ field_value.bool_value = value
145
+ fields[field] = field_value
146
+ new_records.append(FieldValueMapPbo(fields=fields))
147
+ return new_records
148
+
149
+
150
+ class JsonResult(SapioToolResult):
151
+ """
152
+ A class representing JSON results from a Sapio tool.
153
+ """
154
+ json_data: list[Any]
155
+ content_type: str
156
+ file_extensions: list[str]
157
+ name: str
158
+
159
+ def __init__(self, json_data: list[Any], content_type: str = "json", file_extensions: list[str] = None,
160
+ name: str | None = None):
161
+ """
162
+ :param json_data: The list of JSON data results. Each entry in the list represents a separate JSON object.
163
+ These entries must be able to be serialized to JSON using json.dumps().
164
+ :param content_type: The content type of the data.
165
+ :param file_extensions: A list of file extensions that this binary data can be saved as.
166
+ :param name: An optional identifying name for this result that will be accessible to the next tool.
167
+ """
168
+ self.json_data = json_data
169
+ self.content_type = content_type
170
+ self.file_extensions = file_extensions if file_extensions else ["json"]
171
+ self.name = name
172
+
173
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
174
+ return StepOutputBatchPbo(
175
+ item_container=StepItemContainerPbo(
176
+ content_type=ContentTypePbo(name=self.content_type, extensions=self.file_extensions),
177
+ container_name=self.name,
178
+ json_container=StepJsonContainerPbo(items=[json.dumps(x) for x in self.json_data])
179
+ )
180
+ )
181
+
182
+
183
+ class TextResult(SapioToolResult):
184
+ """
185
+ A class representing text results from a Sapio tool.
186
+ """
187
+ text_data: list[str]
188
+ content_type: str
189
+ file_extensions: list[str]
190
+ name: str
191
+
192
+ def __init__(self, text_data: list[str], content_type: str = "text", file_extensions: list[str] = None,
193
+ name: str | None = None):
194
+ """
195
+ :param text_data: The text data as a list of strings.
196
+ :param content_type: The content type of the data.
197
+ :param file_extensions: A list of file extensions that this binary data can be saved as.
198
+ :param name: An optional identifying name for this result that will be accessible to the next tool.
199
+ """
200
+ self.text_data = text_data
201
+ self.content_type = content_type
202
+ self.file_extensions = file_extensions if file_extensions else ["txt"]
203
+ self.name = name
204
+
205
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
206
+ return StepOutputBatchPbo(
207
+ item_container=StepItemContainerPbo(
208
+ content_type=ContentTypePbo(name=self.content_type, extensions=self.file_extensions),
209
+ container_name=self.name,
210
+ text_container=StepTextContainerPbo(items=self.text_data)
211
+ )
212
+ )
213
+
214
+
215
+ class ToolServiceBase(ToolServiceServicer, ABC):
216
+ """
217
+ A base class for implementing a tool service. Subclasses should implement the register_tools method to register
218
+ their tools with the service.
219
+ """
220
+ def GetToolDetails(self, request: ToolDetailsRequestPbo, context: ServicerContext) -> ToolDetailsResponsePbo:
221
+ try:
222
+ # Get the tool details from the registered tools.
223
+ details: list[ToolDetailsPbo] = []
224
+ for tool in self.register_tools():
225
+ details.append(tool().to_pbo())
226
+ if not details:
227
+ raise Exception("No tools registered with this service.")
228
+ return ToolDetailsResponsePbo(tool_framework_version=self.tool_version(), tool_details=details)
229
+ except Exception as e:
230
+ # Woe to you if you somehow cause an exception to be raised when just initializing your tools.
231
+ # There's no way to log this.
232
+ print(f"CRITICAL ERROR: {e}")
233
+ print(traceback.format_exc())
234
+ return ToolDetailsResponsePbo()
235
+
236
+ def ProcessData(self, request: ProcessStepRequestPbo, context: ServicerContext) -> ProcessStepResponsePbo:
237
+ try:
238
+ # Convert the SapioConnectionInfo proto object to a SapioUser object.
239
+ user = self._create_user(request.sapio_user)
240
+ # Get the tool results from the registered tool matching the request.
241
+ success, msg, results, logs = self.run(user, request, context)
242
+ # Convert the results to protobuf objects.
243
+ output_data: list[StepOutputBatchPbo] = []
244
+ new_records: list[FieldValueMapPbo] = []
245
+ for result in results:
246
+ data: StepOutputBatchPbo | list[FieldValueMapPbo] = result.to_proto()
247
+ if isinstance(data, StepOutputBatchPbo):
248
+ output_data.append(data)
249
+ else:
250
+ new_records.extend(data)
251
+ # Return a ProcessStepResponse proto object containing the results to the caller.
252
+ status = ProcessStepResponseStatusPbo.SUCCESS if success else ProcessStepResponseStatusPbo.FAILURE
253
+ return ProcessStepResponsePbo(status=status, status_message=msg, output=output_data, log=logs,
254
+ new_records=new_records)
255
+ except Exception as e:
256
+ # This try/except should never be needed, as the tool should handle its own exceptions, but better safe
257
+ # than sorry.
258
+ print(f"CRITICAL ERROR: {e}")
259
+ print(traceback.format_exc())
260
+ return ProcessStepResponsePbo(status=ProcessStepResponseStatusPbo.FAILURE,
261
+ status_message=f"CRITICAL ERROR: {e}",
262
+ log=[traceback.format_exc()])
263
+
264
+ @staticmethod
265
+ def _create_user(info: SapioConnectionInfoPbo, timeout_seconds: int = 60) -> SapioUser:
266
+ """
267
+ Create a SapioUser object from the given SapioConnectionInfo proto object.
268
+
269
+ :param info: The SapioConnectionInfo proto object.
270
+ :param timeout_seconds: The request timeout for calls made from this user object.
271
+ """
272
+ user = SapioUser(info.webservice_url, True, timeout_seconds, guid=info.app_guid)
273
+ match info.secret_type:
274
+ case SapioUserSecretTypePbo.SESSION_TOKEN:
275
+ user.api_token = info.secret
276
+ case SapioUserSecretTypePbo.PASSWORD:
277
+ secret: str = info.secret
278
+ if secret.startswith("Basic "):
279
+ secret = secret[6:]
280
+ credentials: list[str] = base64.b64decode(secret).decode().split(":", 1)
281
+ user.username = credentials[0]
282
+ user.password = credentials[1]
283
+ case _:
284
+ raise Exception(f"Unexpected secret type: {info.secret_type}")
285
+ return user
286
+
287
+ @staticmethod
288
+ def tool_version() -> int:
289
+ """
290
+ :return: The version of this set of tools.
291
+ """
292
+ return 1
293
+
294
+ @abstractmethod
295
+ def register_tools(self) -> list[type[ToolBase]]:
296
+ """
297
+ Register tool types with this service. Provided tools should implement the ToolBase class.
298
+
299
+ :return: A list of tools to register to this service.
300
+ """
301
+ pass
302
+
303
+ def run(self, user: SapioUser, request: ProcessStepRequestPbo, context: ServicerContext) \
304
+ -> tuple[bool, str, list[SapioToolResult], list[str]]:
305
+ """
306
+ Execute a tool from this service.
307
+
308
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
309
+ system.
310
+ :param request: The request object containing the input data.
311
+ :param context: The gRPC context.
312
+ :return: Whether or not the tool succeeded, the status message, the results of the tool, and any logs
313
+ generated by the tool.
314
+ """
315
+ # Locate the tool named in the request.
316
+ find_tool: str = request.tool_name
317
+ registered_tools: dict[str, type[ToolBase]] = {t.name(): t for t in self.register_tools()}
318
+ if find_tool not in registered_tools:
319
+ # If the tool is not found, list all of the registered tools for this service so that the LLM can correct
320
+ # the tool it is requesting.
321
+ all_tool_names: str = "\n".join(registered_tools.keys())
322
+ msg: str = (f"Tool \"{find_tool}\" not found in the registered tools for this service. The registered "
323
+ f"tools for this service are: \n{all_tool_names}")
324
+ return False, msg, [], []
325
+
326
+ # Instantiate the tool class.
327
+ tool: ToolBase = registered_tools[find_tool]()
328
+ try:
329
+ # Setup the tool with details from the request.
330
+ tool.setup(user, request, context)
331
+ # Validate that the provided inputs match the tool's expected inputs.
332
+ if len(request.input) != len(tool.input_configs):
333
+ msg: str = (f"Expected {len(tool.input_configs)} inputs for this tool, but got {len(request.input)} "
334
+ f"instead.")
335
+ else:
336
+ msg: str = tool.validate_input()
337
+ # If there is no error message, then the inputs are valid.
338
+ success: bool = not bool(msg)
339
+ # If this is a dry run, then provide the fixed dry run output.
340
+ # Otherwise, if the inputs were successfully validated, then the tool is executed normally.
341
+ results: list[SapioToolResult] = []
342
+ if request.dry_run:
343
+ results = tool.dry_run_output()
344
+ elif success:
345
+ results = tool.run(user)
346
+ # Update the status message to reflect the successful execution of the tool.
347
+ msg = f"{tool.name()} successfully completed."
348
+ return success, msg, results, tool.logs
349
+ except Exception as e:
350
+ tool.log_exception("Exception occurred during tool execution.", e)
351
+ return False, str(e), [], tool.logs
352
+ finally:
353
+ # Clean up any temporary files created by the tool.
354
+ tool.temp_data.cleanup()
355
+
356
+
357
+ class ToolBase(ABC):
358
+ """
359
+ A base class for implementing a tool.
360
+ """
361
+ _name: str
362
+ _description: str
363
+ _data_type_name: str | None
364
+ input_configs: list[ToolInputDetailsPbo]
365
+ _input_container_types: list[ContainerType]
366
+ output_configs: list[ToolOutputDetailsPbo]
367
+ _output_container_types: list[ContainerType]
368
+ config_fields: list[VeloxFieldDefPbo]
369
+
370
+ logs: list[str]
371
+ logger: Logger
372
+ verbose_logging: bool
373
+
374
+ temp_data: TempFileHandler
375
+
376
+ user: SapioUser
377
+ request: ProcessStepRequestPbo
378
+ context: ServicerContext
379
+
380
+ @staticmethod
381
+ @abstractmethod
382
+ def name() -> str:
383
+ """
384
+ :return: The name of the tool. This should be unique across all tools in the service.
385
+ """
386
+ pass
387
+
388
+ @staticmethod
389
+ @abstractmethod
390
+ def description() -> str:
391
+ """
392
+ :return: A description of the tool.
393
+ """
394
+ pass
395
+
396
+ @staticmethod
397
+ def data_type_name() -> str | None:
398
+ """
399
+ :return: The name of the output data type of this tool, if applicable. When this tool returns
400
+ FieldMapResult objects in its run method, this name will be used to set the data type of the output data.
401
+ """
402
+ return None
403
+
404
+ def __init__(self):
405
+ self._name = self.name()
406
+ self._description = self.description()
407
+ self._data_type_name = self.data_type_name()
408
+ self.input_configs = []
409
+ self._input_container_types = []
410
+ self.output_configs = []
411
+ self._output_container_types = []
412
+ self.config_fields = []
413
+ self.temp_data = TempFileHandler()
414
+ self.logs = []
415
+ self.logger = logging.getLogger(f"ToolBase.{self._name}")
416
+ ensure_logger_initialized(self.logger)
417
+
418
+ def setup(self, user: SapioUser, request: ProcessStepRequestPbo, context: ServicerContext) -> None:
419
+ """
420
+ Setup the tool with the user, request, and context. This method can be overridden by subclasses to perform
421
+ additional setup.
422
+
423
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
424
+ system.
425
+ :param request: The request object containing the input data.
426
+ :param context: The gRPC context.
427
+ """
428
+ self.user = user
429
+ self.request = request
430
+ self.context = context
431
+ self.verbose_logging = request.verbose_logging
432
+
433
+ def add_input(self, container_type: ContainerType, content_type: str, display_name: str, description: str,
434
+ structure_example: str | bytes | None = None, validation: str | None = None,
435
+ input_count: tuple[int, int] | None = None, is_paged: bool = False,
436
+ page_size: tuple[int, int] | None = None, max_request_bytes: int | None = None) -> None:
437
+ """
438
+ Add an input configuration to the tool. This determines how many inputs this tool will accept in the plan
439
+ manager, as well as what those inputs are. The IO number of the input will be set to the current number of
440
+ inputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
441
+ number will be 1, and so on.
442
+
443
+ :param container_type: The container type of the input.
444
+ :param content_type: The content type of the input.
445
+ :param display_name: The display name of the input.
446
+ :param description: The description of the input.
447
+ :param structure_example: An optional example of the structure of the input, such as how the structure of a
448
+ JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
449
+ brevity.
450
+ :param validation: An optional validation string for the input.
451
+ :param input_count: A tuple of the minimum and maximum number of inputs allowed for this tool.
452
+ :param is_paged: If true, this input will be paged. If false, this input will not be paged.
453
+ :param page_size: A tuple of the minimum and maximum page size for this tool. The input must be paged in order
454
+ for this to have an effect.
455
+ :param max_request_bytes: The maximum request size in bytes for this tool.
456
+ """
457
+ structure: ExampleContainerPbo | None = None
458
+ if isinstance(structure_example, str):
459
+ structure = ExampleContainerPbo(text_example=structure_example)
460
+ elif isinstance(structure_example, bytes):
461
+ structure = ExampleContainerPbo(binary_example=structure_example)
462
+ self.input_configs.append(ToolInputDetailsPbo(
463
+ base_config=ToolIoConfigBasePbo(
464
+ io_number=len(self.input_configs),
465
+ content_type=content_type,
466
+ display_name=display_name,
467
+ description=description,
468
+ structure_example=structure
469
+ ),
470
+ validation=validation,
471
+ min_input_count=input_count[0] if input_count else None,
472
+ max_input_count=input_count[1] if input_count else None,
473
+ paged=is_paged,
474
+ min_page_size=page_size[0] if page_size else None,
475
+ max_page_size=page_size[1] if page_size else None,
476
+ max_request_bytes=max_request_bytes,
477
+ ))
478
+ self._input_container_types.append(container_type)
479
+
480
+ def add_output(self, container_type: ContainerType, content_type: str, display_name: str, description: str,
481
+ testing_example: str | bytes, structure_example: str | bytes | None = None) -> None:
482
+ """
483
+ Add an output configuration to the tool. This determines how many inputs this tool will accept in the plan
484
+ manager, as well as what those inputs are. The IO number of the output will be set to the current number of
485
+ outputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
486
+ number will be 1, and so on.
487
+
488
+ :param container_type: The container type of the output.
489
+ :param content_type: The content type of the output.
490
+ :param display_name: The display name of the output.
491
+ :param description: The description of the output.
492
+ :param testing_example: An example of the input to be used when testing this tool in the system. This must be
493
+ an entirely valid example of what an output of this tool could look like so that it can be properly used
494
+ to run tests with. The provided example may be a string, such as for representing JSON or CSV outputs,
495
+ or bytes, such as for representing binary outputs like images or files.
496
+ :param structure_example: An optional example of the structure of the input, such as how the structure of a
497
+ JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
498
+ brevity.
499
+ """
500
+ testing: ExampleContainerPbo | None = None
501
+ if isinstance(testing_example, str):
502
+ testing = ExampleContainerPbo(text_example=testing_example)
503
+ elif isinstance(testing_example, bytes):
504
+ testing = ExampleContainerPbo(binary_example=testing_example)
505
+
506
+ structure: ExampleContainerPbo | None = None
507
+ if isinstance(structure_example, str):
508
+ structure = ExampleContainerPbo(text_example=structure_example)
509
+ elif isinstance(structure_example, bytes):
510
+ structure = ExampleContainerPbo(binary_example=structure_example)
511
+
512
+ self.output_configs.append(ToolOutputDetailsPbo(
513
+ base_config=ToolIoConfigBasePbo(
514
+ io_number=len(self.output_configs),
515
+ content_type=content_type,
516
+ display_name=display_name,
517
+ description=description,
518
+ structure_example=structure,
519
+ testing_example=testing
520
+ )))
521
+ self._output_container_types.append(container_type)
522
+
523
+ def add_config_field(self, field: VeloxFieldDefPbo) -> None:
524
+ """
525
+ Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
526
+
527
+ :param field: The configuration field details.
528
+ """
529
+ self.config_fields.append(field)
530
+
531
+ def add_config_field_def(self, field: AbstractVeloxFieldDefinition) -> None:
532
+ """
533
+ Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
534
+
535
+ :param field: The configuration field details.
536
+ """
537
+ self.config_fields.append(ProtobufUtils.field_def_to_pbo(field))
538
+
539
+ def add_boolean_config_field(self, field_name: str, display_name: str, description: str,
540
+ default_value: bool | None = None, optional: bool = False) -> None:
541
+ """
542
+ Add a boolean configuration field to the tool. This field will be used to configure the tool in the plan
543
+ manager.
544
+
545
+ :param field_name: The name of the field.
546
+ :param display_name: The display name of the field.
547
+ :param description: The description of the field.
548
+ :param default_value: The default value of the field.
549
+ :param optional: If true, this field is optional. If false, this field is required.
550
+ """
551
+ self.config_fields.append(VeloxFieldDefPbo(
552
+ data_field_type=FieldTypePbo.BOOLEAN,
553
+ data_field_name=field_name,
554
+ display_name=display_name,
555
+ description=description,
556
+ required=not optional,
557
+ editable=True,
558
+ boolean_properties=BooleanPropertiesPbo(
559
+ default_value=default_value
560
+ )
561
+ ))
562
+
563
+ def add_double_config_field(self, field_name: str, display_name: str, description: str,
564
+ default_value: float | None = None, min_value: float = -10.**120,
565
+ max_value: float = 10.**120, precision: int = 2, optional: bool = False) -> None:
566
+ """
567
+ Add a double configuration field to the tool. This field will be used to configure the tool in the plan
568
+ manager.
569
+
570
+ :param field_name: The name of the field.
571
+ :param display_name: The display name of the field.
572
+ :param description: The description of the field.
573
+ :param default_value: The default value of the field.
574
+ :param min_value: The minimum value of the field.
575
+ :param max_value: The maximum value of the field.
576
+ :param precision: The precision of the field.
577
+ :param optional: If true, this field is optional. If false, this field is required.
578
+ """
579
+ self.config_fields.append(VeloxFieldDefPbo(
580
+ data_field_type=FieldTypePbo.DOUBLE,
581
+ data_field_name=field_name,
582
+ display_name=display_name,
583
+ description=description,
584
+ required=not optional,
585
+ editable=True,
586
+ double_properties=DoublePropertiesPbo(
587
+ default_value=default_value,
588
+ min_value=min_value,
589
+ max_value=max_value,
590
+ precision=precision
591
+ )
592
+ ))
593
+
594
+ def add_integer_config_field(self, field_name: str, display_name: str, description: str,
595
+ default_value: int | None = None, min_value: int = -2**31, max_value: int = 2**31-1,
596
+ optional: bool = False) -> None:
597
+ """
598
+ Add an integer configuration field to the tool. This field will be used to configure the tool in the plan
599
+ manager.
600
+
601
+ :param field_name: The name of the field.
602
+ :param display_name: The display name of the field.
603
+ :param description: The description of the field.
604
+ :param default_value: The default value of the field.
605
+ :param min_value: The minimum value of the field.
606
+ :param max_value: The maximum value of the field.
607
+ :param optional: If true, this field is optional. If false, this field is required.
608
+ """
609
+ self.config_fields.append(VeloxFieldDefPbo(
610
+ data_field_type=FieldTypePbo.INTEGER,
611
+ data_field_name=field_name,
612
+ display_name=display_name,
613
+ description=description,
614
+ required=not optional,
615
+ editable=True,
616
+ integer_properties=IntegerPropertiesPbo(
617
+ default_value=default_value,
618
+ min_value=min_value,
619
+ max_value=max_value
620
+ )
621
+ ))
622
+
623
+ def add_string_config_field(self, field_name: str, display_name: str, description: str,
624
+ default_value: str | None = None, max_length: int = 1000, optional: bool = False) \
625
+ -> None:
626
+ """
627
+ Add a string configuration field to the tool. This field will be used to configure the tool in the plan
628
+ manager.
629
+
630
+ :param field_name: The name of the field.
631
+ :param display_name: The display name of the field.
632
+ :param description: The description of the field.
633
+ :param default_value: The default value of the field.
634
+ :param max_length: The maximum length of the field.
635
+ :param optional: If true, this field is optional. If false, this field is required.
636
+ """
637
+ self.config_fields.append(VeloxFieldDefPbo(
638
+ data_field_type=FieldTypePbo.STRING,
639
+ data_field_name=field_name,
640
+ display_name=display_name,
641
+ description=description,
642
+ required=not optional,
643
+ editable=True,
644
+ string_properties=StringPropertiesPbo(
645
+ default_value=default_value,
646
+ max_length=max_length
647
+ )
648
+ ))
649
+
650
+ def add_list_config_field(self, field_name: str, display_name: str, description: str,
651
+ default_value: str | None = None, allowed_values: list[str] | None = None,
652
+ direct_edit: bool = False, optional: bool = False) -> None:
653
+ """
654
+ Add a list configuration field to the tool. This field will be used to configure the tool in the plan
655
+ manager.
656
+
657
+ :param field_name: The name of the field.
658
+ :param display_name: The display name of the field.
659
+ :param description: The description of the field.
660
+ :param default_value: The default value of the field.
661
+ :param allowed_values: The list of allowed values for the field.
662
+ :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
663
+ the user can only select from the list of allowed values.
664
+ :param optional: If true, this field is optional. If false, this field is required.
665
+ """
666
+ self.config_fields.append(VeloxFieldDefPbo(
667
+ data_field_type=FieldTypePbo.SELECTION,
668
+ data_field_name=field_name,
669
+ display_name=display_name,
670
+ description=description,
671
+ required=not optional,
672
+ editable=True,
673
+ selection_properties=SelectionPropertiesPbo(
674
+ default_value=default_value,
675
+ static_list_values=allowed_values,
676
+ direct_edit=direct_edit,
677
+ )
678
+ ))
679
+
680
+ def add_multi_list_config_field(self, field_name: str, display_name: str, description: str,
681
+ default_value: list[str] | None = None, allowed_values: list[str] | None = None,
682
+ direct_edit: bool = False, optional: bool = False) -> None:
683
+ """
684
+ Add a multi-select list configuration field to the tool. This field will be used to configure the tool in the
685
+ plan manager.
686
+
687
+ :param field_name: The name of the field.
688
+ :param display_name: The display name of the field.
689
+ :param description: The description of the field.
690
+ :param default_value: The default value of the field.
691
+ :param allowed_values: The list of allowed values for the field.
692
+ :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
693
+ the user can only select from the list of allowed values.
694
+ :param optional: If true, this field is optional. If false, this field is required.
695
+ """
696
+ self.config_fields.append(VeloxFieldDefPbo(
697
+ data_field_type=FieldTypePbo.SELECTION,
698
+ data_field_name=field_name,
699
+ display_name=display_name,
700
+ description=description,
701
+ required=not optional,
702
+ editable=True,
703
+ selection_properties=SelectionPropertiesPbo(
704
+ default_value=",".join(default_value) if default_value else None,
705
+ static_list_values=allowed_values,
706
+ multi_select=True,
707
+ direct_edit=direct_edit,
708
+ )
709
+ ))
710
+
711
+ def to_pbo(self) -> ToolDetailsPbo:
712
+ """
713
+ :return: The ToolDetailsPbo proto object representing this tool.
714
+ """
715
+ return ToolDetailsPbo(
716
+ name=self._name,
717
+ description=self._description,
718
+ input_configs=self.input_configs,
719
+ output_configs=self.output_configs,
720
+ output_data_type_name=self._data_type_name,
721
+ config_fields=self.config_fields
722
+ )
723
+
724
+ @abstractmethod
725
+ def validate_input(self) -> str | None:
726
+ """
727
+ Validate the request given to this tool. If the request is validly formatted, this method should return None.
728
+ If the request is not valid, this method should return an error message indicating what is wrong with the
729
+ request.
730
+
731
+ This method should not perform any actual processing of the request. It should only validate the inputs and
732
+ configurations provided in the request.
733
+
734
+ The request inputs can be accessed using the self.get_input_*() methods.
735
+ The request settings can be accessed using the self.get_config_fields() method.
736
+ The request itself can be accessed using self.request.
737
+
738
+ :return: A tuple containing a boolean indicating whether the request is valid and a message describing the
739
+ result of the validation.
740
+ """
741
+ pass
742
+
743
+ def dry_run_output(self) -> list[SapioToolResult]:
744
+ """
745
+ Provide fixed results for a dry run of this tool. This method should not perform any actual processing of the
746
+ request. It should only return example outputs that can be used to test the next tool in the plan.
747
+
748
+ The default implementation of this method looks at the testing_example field of each output configuration
749
+ and returns a SapioToolResult object based on the content type of the output.
750
+
751
+ :return: A list of SapioToolResult objects containing example outputs for this tool. Each result in the list
752
+ corresponds to a separate output from the tool.
753
+ """
754
+ results: list[SapioToolResult] = []
755
+ for output, container_type in zip(self.output_configs, self._output_container_types):
756
+ config: ToolIoConfigBasePbo = output.base_config
757
+ example: ExampleContainerPbo = config.testing_example
758
+ content_type: str = config.content_type
759
+ match container_type:
760
+ case ContainerType.BINARY:
761
+ example: bytes = example.binary_example
762
+ results.append(BinaryResult(binary_data=[example], content_type=content_type))
763
+ case ContainerType.CSV:
764
+ example: str = example.text_example
765
+ results.append(CsvResult(FileUtil.tokenize_csv(example.encode())[0], content_type=content_type))
766
+ case ContainerType.JSON:
767
+ # The example may be in the JSONL format instead of plain JSON, so we need to use Pandas to parse
768
+ # the example into plain JSON.
769
+ example: str = example.text_example
770
+ # Format the JSONL in a way that Pandas likes. Collapse everything into a single line, and then
771
+ # split it back into multiple lines where each line is a single JSON list or dictionary.
772
+ example: str = re.sub("([]}])\s*([\[{])", r"\1\n\2", example.replace("\n", "")).strip()
773
+ # Read the JSONL into a Pandas DataFrame and convert it back to plain JSON.
774
+ import pandas as pd
775
+ with io.StringIO(example) as stream:
776
+ example: str = pd.read_json(path_or_buf=stream, lines=True).to_json()
777
+ results.append(JsonResult(json_data=[json.loads(example)], content_type=content_type))
778
+ case ContainerType.TEXT:
779
+ example: str = example.text_example
780
+ results.append(TextResult(text_data=[example], content_type=content_type))
781
+ return results
782
+
783
+ @abstractmethod
784
+ def run(self, user: SapioUser) -> list[SapioToolResult]:
785
+ """
786
+ Execute this tool.
787
+
788
+ The request inputs can be accessed using the self.get_input_*() methods.
789
+ The request settings can be accessed using the self.get_config_fields() method.
790
+ The request itself can be accessed using self.request.
791
+
792
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
793
+ system.
794
+ :return: A list of SapioToolResult objects containing the response data. Each result in the list corresponds to
795
+ a separate output from the tool. Field map results do not appear as tool output in the plan manager, instead
796
+ appearing as records related to the plan step during the run.
797
+ """
798
+ pass
799
+
800
+ def log_info(self, message: str) -> None:
801
+ """
802
+ Log an info message for this tool. If verbose logging is enabled, this message will be included in the logs
803
+ returned to the caller. Empty/None inputs will not be logged.
804
+
805
+ :param message: The message to log.
806
+ """
807
+ if not message:
808
+ return
809
+ if self.verbose_logging:
810
+ self.logs.append(f"INFO: {self._name}: {message}")
811
+ self.logger.info(message)
812
+
813
+ def log_warning(self, message: str) -> None:
814
+ """
815
+ Log a warning message for this tool. This message will be included in the logs returned to the caller.
816
+ Empty/None inputs will not be logged.
817
+
818
+ :param message: The message to log.
819
+ """
820
+ if not message:
821
+ return
822
+ self.logs.append(f"WARNING: {self._name}: {message}")
823
+ self.logger.warning(message)
824
+
825
+ def log_error(self, message: str) -> None:
826
+ """
827
+ Log an error message for this tool. This message will be included in the logs returned to the caller.
828
+ Empty/None inputs will not be logged.
829
+
830
+ :param message: The message to log.
831
+ """
832
+ if not message:
833
+ return
834
+ self.logs.append(f"ERROR: {self._name}: {message}")
835
+ self.logger.error(message)
836
+
837
+ def log_exception(self, message: str, e: Exception) -> None:
838
+ """
839
+ Log an exception for this tool. This message will be included in the logs returned to the caller.
840
+ Empty/None inputs will not be logged.
841
+
842
+ :param message: The message to log.
843
+ :param e: The exception to log.
844
+ """
845
+ if not message and not e:
846
+ return
847
+ self.logs.append(f"EXCEPTION: {self._name}: {message} - {e}")
848
+ self.logger.error(f"{message}\n{traceback.format_exc()}")
849
+
850
+ def get_input_name(self, index: int = 0) -> str | None:
851
+ """
852
+ Get the name of the input from the request object.
853
+
854
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
855
+ :return: The name of the input from the request object, or None if no name is set.
856
+ """
857
+ return self.request.input[index].item_container.container_name
858
+
859
+ def get_input_binary(self, index: int = 0) -> list[bytes]:
860
+ """
861
+ Get the binary data from the request object.
862
+
863
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
864
+ :return: The binary data from the request object.
865
+ """
866
+ return list(self.request.input[index].item_container.binary_container.items)
867
+
868
+ def get_input_csv(self, index: int = 0) -> tuple[list[str], list[dict[str, str]]]:
869
+ """
870
+ Parse the CSV data from the request object.
871
+
872
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
873
+ :return: A tuple containing the header row and the data rows. The header row is a list of strings representing
874
+ the column names, and the data rows are a list of dictionaries where each dictionary represents a row in the
875
+ CSV with the column names as keys and the corresponding values as strings.
876
+ """
877
+ input_data: Sequence[StepInputBatchPbo] = self.request.input
878
+ ret_val: list[dict[str, str]] = []
879
+ headers: Iterable[str] = input_data[index].item_container.csv_container.header.cells
880
+ for row in input_data[index].item_container.csv_container.items:
881
+ row_dict: dict[str, str] = {}
882
+ for header, value in zip(headers, row.cells):
883
+ row_dict[header] = value
884
+ ret_val.append(row_dict)
885
+ return list(headers), ret_val
886
+
887
+ def get_input_json(self, index: int = 0) -> list[list[Any]] | list[dict[str, Any]]:
888
+ """
889
+ Parse the JSON data from the request object.
890
+
891
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
892
+ :return: A list of parsed JSON objects. Each entry in the list represents a separate JSON entry from the input.
893
+ Depending on this tool, this may be a list of dictionaries or a list of lists.
894
+ """
895
+ return [json.loads(x) for x in self.request.input[index].item_container.json_container.items]
896
+
897
+ def get_input_text(self, index: int = 0) -> list[str]:
898
+ """
899
+ Parse the text data from the request object.
900
+
901
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
902
+ :return: A list of text data as strings.
903
+ """
904
+ return list(self.request.input[index].item_container.text_container.items)
905
+
906
+ def get_config_defs(self) -> dict[str, VeloxFieldDefPbo]:
907
+ """
908
+ Get the config field definitions for this tool.
909
+
910
+ :return: A dictionary of field definitions, where the keys are the field names and the values are the
911
+ VeloxFieldDefPbo objects representing the field definitions.
912
+ """
913
+ field_defs: dict[str, VeloxFieldDefPbo] = {}
914
+ for field_def in self.to_pbo().config_fields:
915
+ field_defs[field_def.data_field_name] = field_def
916
+ return field_defs
917
+
918
+ def get_config_fields(self) -> dict[str, FieldValue | list[str]]:
919
+ """
920
+ Get the configuration field values from the request object. If a field is not present in the request,
921
+ the default value from the config definition will be returned.
922
+
923
+ :return: A dictionary of configuration field names and their values. For multi-select selection list fields,
924
+ a list of strings will be returned. For all other field types, the value will match the field type
925
+ (bool for boolean fields, float for double fields, int for short, integer, long, and enum fields, and
926
+ string for everything else).
927
+ """
928
+ config_fields: dict[str, Any] = {}
929
+ raw_configs: Mapping[str, FieldValuePbo] = self.request.config_field_values
930
+ for field_name, field_def in self.get_config_defs().items():
931
+ field_value: FieldValue = None
932
+ # If the field is present in the request, convert the protobuf value to a Python value.
933
+ if field_name in raw_configs:
934
+ field_value = ProtobufUtils.field_pbo_to_value(raw_configs[field_name])
935
+ # If the field isn't present or is None, use the default value from the field definition.
936
+ if field_value is None:
937
+ field_value = ProtobufUtils.field_def_pbo_to_default_value(field_def)
938
+ # If the field is a multi-select selection list, split the value by commas and strip whitespace.
939
+ if field_def.data_field_type == FieldTypePbo.SELECTION and field_def.selection_properties.multi_select:
940
+ field_value: list[str] = [x.strip() for x in field_value.split(',') if x.strip()]
941
+ config_fields[field_name] = field_value
942
+ return config_fields
943
+
944
+ @staticmethod
945
+ def read_from_json(json_data: list[dict[str, Any]], key: str) -> list[Any]:
946
+ """
947
+ From a list of dictionaries, return a list of values for the given key from each dictionary. Skips null values.
948
+
949
+ :param json_data: The JSON data to read from.
950
+ :param key: The key to read the values from.
951
+ :return: A list of values corresponding to the given key in the JSON data.
952
+ """
953
+ ret_val: list[Any] = []
954
+ for entry in json_data:
955
+ if key in entry:
956
+ value = entry[key]
957
+ if isinstance(value, list):
958
+ ret_val.extend(value)
959
+ elif value is not None:
960
+ ret_val.append(value)
961
+ return ret_val