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