sapiopycommons 2025.8.14a702__py3-none-any.whl → 2025.8.14a703__py3-none-any.whl

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