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