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