sapiopycommons 2025.8.22a715__py3-none-any.whl → 2025.8.22a716__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 (49) hide show
  1. sapiopycommons/ai/tool_of_tools.py +917 -0
  2. sapiopycommons/callbacks/callback_util.py +26 -16
  3. sapiopycommons/chem/IndigoMolecules.py +12 -10
  4. sapiopycommons/chem/ps_commons.py +773 -0
  5. sapiopycommons/files/assay_plate_reader.py +93 -0
  6. sapiopycommons/files/file_text_converter.py +207 -0
  7. sapiopycommons/flowcyto/flow_cyto.py +2 -24
  8. sapiopycommons/general/accession_service.py +2 -28
  9. sapiopycommons/multimodal/multimodal.py +2 -24
  10. sapiopycommons/webhook/webservice_handlers.py +1 -1
  11. {sapiopycommons-2025.8.22a715.dist-info → sapiopycommons-2025.8.22a716.dist-info}/METADATA +2 -2
  12. {sapiopycommons-2025.8.22a715.dist-info → sapiopycommons-2025.8.22a716.dist-info}/RECORD +14 -45
  13. sapiopycommons/ai/converter_service_base.py +0 -131
  14. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2.py +0 -43
  15. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2.pyi +0 -31
  16. sapiopycommons/ai/protoapi/fielddefinitions/fields_pb2_grpc.py +0 -24
  17. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2.py +0 -123
  18. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2.pyi +0 -598
  19. sapiopycommons/ai/protoapi/fielddefinitions/velox_field_def_pb2_grpc.py +0 -24
  20. sapiopycommons/ai/protoapi/plan/converter/converter_pb2.py +0 -51
  21. sapiopycommons/ai/protoapi/plan/converter/converter_pb2.pyi +0 -63
  22. sapiopycommons/ai/protoapi/plan/converter/converter_pb2_grpc.py +0 -149
  23. sapiopycommons/ai/protoapi/plan/item/item_container_pb2.py +0 -55
  24. sapiopycommons/ai/protoapi/plan/item/item_container_pb2.pyi +0 -88
  25. sapiopycommons/ai/protoapi/plan/item/item_container_pb2_grpc.py +0 -24
  26. sapiopycommons/ai/protoapi/plan/script/script_pb2.py +0 -59
  27. sapiopycommons/ai/protoapi/plan/script/script_pb2.pyi +0 -102
  28. sapiopycommons/ai/protoapi/plan/script/script_pb2_grpc.py +0 -153
  29. sapiopycommons/ai/protoapi/plan/step_output_pb2.py +0 -45
  30. sapiopycommons/ai/protoapi/plan/step_output_pb2.pyi +0 -42
  31. sapiopycommons/ai/protoapi/plan/step_output_pb2_grpc.py +0 -24
  32. sapiopycommons/ai/protoapi/plan/step_pb2.py +0 -43
  33. sapiopycommons/ai/protoapi/plan/step_pb2.pyi +0 -43
  34. sapiopycommons/ai/protoapi/plan/step_pb2_grpc.py +0 -24
  35. sapiopycommons/ai/protoapi/plan/tool/entry_pb2.py +0 -41
  36. sapiopycommons/ai/protoapi/plan/tool/entry_pb2.pyi +0 -35
  37. sapiopycommons/ai/protoapi/plan/tool/entry_pb2_grpc.py +0 -24
  38. sapiopycommons/ai/protoapi/plan/tool/tool_pb2.py +0 -75
  39. sapiopycommons/ai/protoapi/plan/tool/tool_pb2.pyi +0 -237
  40. sapiopycommons/ai/protoapi/plan/tool/tool_pb2_grpc.py +0 -154
  41. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2.py +0 -39
  42. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2.pyi +0 -32
  43. sapiopycommons/ai/protoapi/session/sapio_conn_info_pb2_grpc.py +0 -24
  44. sapiopycommons/ai/protobuf_utils.py +0 -504
  45. sapiopycommons/ai/server.py +0 -104
  46. sapiopycommons/ai/test_client.py +0 -356
  47. sapiopycommons/ai/tool_service_base.py +0 -922
  48. {sapiopycommons-2025.8.22a715.dist-info → sapiopycommons-2025.8.22a716.dist-info}/WHEEL +0 -0
  49. {sapiopycommons-2025.8.22a715.dist-info → sapiopycommons-2025.8.22a716.dist-info}/licenses/LICENSE +0 -0
@@ -1,922 +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.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 len(request.input) != len(tool.input_configs):
312
- msg: str = f"Expected {len(tool.input_configs)} inputs for this tool, but got {len(request.input)} instead."
313
- else:
314
- msg: str = tool.validate_input()
315
- # If there is no error message, then the inputs are valid.
316
- success: bool = not bool(msg)
317
- # If this is a dry run, then provide the fixed dry run output.
318
- # Otherwise, if the inputs were successfully validated, then the tool is executed normally.
319
- results: list[SapioToolResult] = []
320
- if request.dry_run:
321
- results = tool.dry_run_output()
322
- elif success:
323
- results = tool.run(user)
324
- # Update the status message to reflect the successful execution of the tool.
325
- msg = f"{tool.name()} successfully completed."
326
- return success, msg, results, tool.logs
327
- except Exception as e:
328
- tool.log_exception("Exception occurred during tool execution.", e)
329
- return False, str(e), [], tool.logs
330
-
331
-
332
- class ToolBase(ABC):
333
- """
334
- A base class for implementing a tool.
335
- """
336
- _name: str
337
- _description: str
338
- _data_type_name: str | None
339
- input_configs: list[ToolInputDetailsPbo]
340
- _input_container_types: list[ContainerType]
341
- output_configs: list[ToolOutputDetailsPbo]
342
- _output_container_types: list[ContainerType]
343
- config_fields: list[VeloxFieldDefPbo]
344
-
345
- logs: list[str]
346
- logger: Logger
347
- verbose_logging: bool
348
-
349
- user: SapioUser
350
- request: ProcessStepRequestPbo
351
- context: ServicerContext
352
-
353
- @staticmethod
354
- @abstractmethod
355
- def name() -> str:
356
- """
357
- :return: The name of the tool. This should be unique across all tools in the service.
358
- """
359
- pass
360
-
361
- @staticmethod
362
- @abstractmethod
363
- def description() -> str:
364
- """
365
- :return: A description of the tool.
366
- """
367
- pass
368
-
369
- @staticmethod
370
- def data_type_name() -> str | None:
371
- """
372
- :return: The name of the output data type of this tool, if applicable. When this tool returns
373
- FieldMapResult objects in its run method, this name will be used to set the data type of the output data.
374
- """
375
- return None
376
-
377
- def __init__(self):
378
- self._name = self.name()
379
- self._description = self.description()
380
- self._data_type_name = self.data_type_name()
381
- self.input_configs = []
382
- self._input_container_types = []
383
- self.output_configs = []
384
- self._output_container_types = []
385
- self.config_fields = []
386
- self.logs = []
387
- self.logger = logging.getLogger(f"ToolBase.{self._name}")
388
- ensure_logger_initialized(self.logger)
389
-
390
- def setup(self, user: SapioUser, request: ProcessStepRequestPbo, context: ServicerContext) -> None:
391
- """
392
- Setup the tool with the user, request, and context. This method can be overridden by subclasses to perform
393
- additional setup.
394
-
395
- :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
396
- system.
397
- :param request: The request object containing the input data.
398
- :param context: The gRPC context.
399
- """
400
- self.user = user
401
- self.request = request
402
- self.context = context
403
- self.verbose_logging = request.verbose_logging
404
-
405
- def add_input(self, container_type: ContainerType, content_type: str, display_name: str, description: str,
406
- structure_example: str | bytes | None = None, validation: str | None = None,
407
- input_count: tuple[int, int] | None = None, is_paged: bool = False,
408
- page_size: tuple[int, int] | None = None, max_request_bytes: int | None = None) -> None:
409
- """
410
- Add an input configuration to the tool. This determines how many inputs this tool will accept in the plan
411
- manager, as well as what those inputs are. The IO number of the input will be set to the current number of
412
- inputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
413
- number will be 1, and so on.
414
-
415
- :param container_type: The container type of the input.
416
- :param content_type: The content type of the input.
417
- :param display_name: The display name of the input.
418
- :param description: The description of the input.
419
- :param structure_example: An optional example of the structure of the input, such as how the structure of a
420
- JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
421
- brevity.
422
- :param validation: An optional validation string for the input.
423
- :param input_count: A tuple of the minimum and maximum number of inputs allowed for this tool.
424
- :param is_paged: If true, this input will be paged. If false, this input will not be paged.
425
- :param page_size: A tuple of the minimum and maximum page size for this tool. The input must be paged in order
426
- for this to have an effect.
427
- :param max_request_bytes: The maximum request size in bytes for this tool.
428
- """
429
- structure: ExampleContainerPbo | None = None
430
- if isinstance(structure_example, str):
431
- structure = ExampleContainerPbo(text_example=structure_example)
432
- elif isinstance(structure_example, bytes):
433
- structure = ExampleContainerPbo(binary_example=structure_example)
434
- self.input_configs.append(ToolInputDetailsPbo(
435
- base_config=ToolIoConfigBasePbo(
436
- io_number=len(self.input_configs),
437
- content_type=content_type,
438
- display_name=display_name,
439
- description=description,
440
- structure_example=structure
441
- ),
442
- validation=validation,
443
- min_input_count=input_count[0] if input_count else None,
444
- max_input_count=input_count[1] if input_count else None,
445
- paged=is_paged,
446
- min_page_size=page_size[0] if page_size else None,
447
- max_page_size=page_size[1] if page_size else None,
448
- max_request_bytes=max_request_bytes,
449
- ))
450
- self._input_container_types.append(container_type)
451
-
452
- def add_output(self, container_type: ContainerType, content_type: str, display_name: str, description: str,
453
- testing_example: str | bytes, structure_example: str | bytes | None = None) -> None:
454
- """
455
- Add an output configuration to the tool. This determines how many inputs this tool will accept in the plan
456
- manager, as well as what those inputs are. The IO number of the output will be set to the current number of
457
- outputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
458
- number will be 1, and so on.
459
-
460
- :param container_type: The container type of the output.
461
- :param content_type: The content type of the output.
462
- :param display_name: The display name of the output.
463
- :param description: The description of the output.
464
- :param testing_example: An example of the input to be used when testing this tool in the system. This must be
465
- an entirely valid example of what an output of this tool could look like so that it can be properly used
466
- to run tests with. The provided example may be a string, such as for representing JSON or CSV outputs,
467
- or bytes, such as for representing binary outputs like images or files.
468
- :param structure_example: An optional example of the structure of the input, such as how the structure of a
469
- JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
470
- brevity.
471
- """
472
- testing: ExampleContainerPbo | None = None
473
- if isinstance(testing_example, str):
474
- testing = ExampleContainerPbo(text_example=testing_example)
475
- elif isinstance(testing_example, bytes):
476
- testing = ExampleContainerPbo(binary_example=testing_example)
477
-
478
- structure: ExampleContainerPbo | None = None
479
- if isinstance(structure_example, str):
480
- structure = ExampleContainerPbo(text_example=structure_example)
481
- elif isinstance(structure_example, bytes):
482
- structure = ExampleContainerPbo(binary_example=structure_example)
483
-
484
- self.output_configs.append(ToolOutputDetailsPbo(
485
- base_config=ToolIoConfigBasePbo(
486
- io_number=len(self.output_configs),
487
- content_type=content_type,
488
- display_name=display_name,
489
- description=description,
490
- structure_example=structure,
491
- testing_example=testing
492
- )))
493
- self._output_container_types.append(container_type)
494
-
495
- def add_config_field(self, field: VeloxFieldDefPbo) -> None:
496
- """
497
- Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
498
-
499
- :param field: The configuration field details.
500
- """
501
- self.config_fields.append(field)
502
-
503
- def add_config_field_def(self, field: AbstractVeloxFieldDefinition) -> None:
504
- """
505
- Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
506
-
507
- :param field: The configuration field details.
508
- """
509
- self.config_fields.append(ProtobufUtils.field_def_to_pbo(field))
510
-
511
- def add_boolean_config_field(self, field_name: str, display_name: str, description: str, default_value: bool,
512
- optional: bool = False) -> None:
513
- """
514
- Add a boolean configuration field to the tool. This field will be used to configure the tool in the plan
515
- manager.
516
-
517
- :param field_name: The name of the field.
518
- :param display_name: The display name of the field.
519
- :param description: The description of the field.
520
- :param default_value: The default value of the field.
521
- :param optional: If true, this field is optional. If false, this field is required.
522
- """
523
- self.config_fields.append(VeloxFieldDefPbo(
524
- data_field_type=FieldTypePbo.BOOLEAN,
525
- data_field_name=field_name,
526
- display_name=display_name,
527
- description=description,
528
- required=not optional,
529
- editable=True,
530
- boolean_properties=BooleanPropertiesPbo(
531
- default_value=default_value
532
- )
533
- ))
534
-
535
- def add_double_config_field(self, field_name: str, display_name: str, description: str, default_value: float,
536
- min_value: float = -10.**120, max_value: float = 10.**120, precision: int = 2,
537
- optional: bool = False) -> None:
538
- """
539
- Add a double configuration field to the tool. This field will be used to configure the tool in the plan
540
- manager.
541
-
542
- :param field_name: The name of the field.
543
- :param display_name: The display name of the field.
544
- :param description: The description of the field.
545
- :param default_value: The default value of the field.
546
- :param min_value: The minimum value of the field.
547
- :param max_value: The maximum value of the field.
548
- :param precision: The precision of the field.
549
- :param optional: If true, this field is optional. If false, this field is required.
550
- """
551
- self.config_fields.append(VeloxFieldDefPbo(
552
- data_field_type=FieldTypePbo.DOUBLE,
553
- data_field_name=field_name,
554
- display_name=display_name,
555
- description=description,
556
- required=not optional,
557
- editable=True,
558
- double_properties=DoublePropertiesPbo(
559
- default_value=default_value,
560
- min_value=min_value,
561
- max_value=max_value,
562
- precision=precision
563
- )
564
- ))
565
-
566
- def add_integer_config_field(self, field_name: str, display_name: str, description: str,
567
- default_value: int, min_value: int = -2**31, max_value: int = 2**31-1,
568
- optional: bool = False) -> None:
569
- """
570
- Add an integer configuration field to the tool. This field will be used to configure the tool in the plan
571
- manager.
572
-
573
- :param field_name: The name of the field.
574
- :param display_name: The display name of the field.
575
- :param description: The description of the field.
576
- :param default_value: The default value of the field.
577
- :param min_value: The minimum value of the field.
578
- :param max_value: The maximum value of the field.
579
- :param optional: If true, this field is optional. If false, this field is required.
580
- """
581
- self.config_fields.append(VeloxFieldDefPbo(
582
- data_field_type=FieldTypePbo.INTEGER,
583
- data_field_name=field_name,
584
- display_name=display_name,
585
- description=description,
586
- required=not optional,
587
- editable=True,
588
- integer_properties=IntegerPropertiesPbo(
589
- default_value=default_value,
590
- min_value=min_value,
591
- max_value=max_value
592
- )
593
- ))
594
-
595
- def add_string_config_field(self, field_name: str, display_name: str, description: str,
596
- default_value: str, max_length: int = 1000, optional: bool = False) -> None:
597
- """
598
- Add a string configuration field to the tool. This field will be used to configure the tool in the plan
599
- manager.
600
-
601
- :param field_name: The name of the field.
602
- :param display_name: The display name of the field.
603
- :param description: The description of the field.
604
- :param default_value: The default value of the field.
605
- :param max_length: The maximum length of the field.
606
- :param optional: If true, this field is optional. If false, this field is required.
607
- """
608
- self.config_fields.append(VeloxFieldDefPbo(
609
- data_field_type=FieldTypePbo.STRING,
610
- data_field_name=field_name,
611
- display_name=display_name,
612
- description=description,
613
- required=not optional,
614
- editable=True,
615
- string_properties=StringPropertiesPbo(
616
- default_value=default_value,
617
- max_length=max_length
618
- )
619
- ))
620
-
621
- def add_list_config_field(self, field_name: str, display_name: str, description: str, default_value: str,
622
- allowed_values: list[str], direct_edit: bool = False, optional: bool = False) -> None:
623
- """
624
- Add a list configuration field to the tool. This field will be used to configure the tool in the plan
625
- manager.
626
-
627
- :param field_name: The name of the field.
628
- :param display_name: The display name of the field.
629
- :param description: The description of the field.
630
- :param default_value: The default value of the field.
631
- :param allowed_values: The list of allowed values for the field.
632
- :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
633
- the user can only select from the list of allowed values.
634
- :param optional: If true, this field is optional. If false, this field is required.
635
- """
636
- self.config_fields.append(VeloxFieldDefPbo(
637
- data_field_type=FieldTypePbo.SELECTION,
638
- data_field_name=field_name,
639
- display_name=display_name,
640
- description=description,
641
- required=not optional,
642
- editable=True,
643
- selection_properties=SelectionPropertiesPbo(
644
- default_value=default_value,
645
- static_list_values=allowed_values,
646
- direct_edit=direct_edit,
647
- )
648
- ))
649
-
650
- def add_multi_list_config_field(self, field_name: str, display_name: str, description: str,
651
- default_value: list[str], allowed_values: list[str], direct_edit: bool = False,
652
- optional: bool = False) -> None:
653
- """
654
- Add a multi-select list configuration field to the tool. This field will be used to configure the tool in the
655
- plan manager.
656
-
657
- :param field_name: The name of the field.
658
- :param display_name: The display name of the field.
659
- :param description: The description of the field.
660
- :param default_value: The default value of the field.
661
- :param allowed_values: The list of allowed values for the field.
662
- :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
663
- the user can only select from the list of allowed values.
664
- :param optional: If true, this field is optional. If false, this field is required.
665
- """
666
- self.config_fields.append(VeloxFieldDefPbo(
667
- data_field_type=FieldTypePbo.SELECTION,
668
- data_field_name=field_name,
669
- display_name=display_name,
670
- description=description,
671
- required=not optional,
672
- editable=True,
673
- selection_properties=SelectionPropertiesPbo(
674
- default_value=",".join(default_value),
675
- static_list_values=allowed_values,
676
- multi_select=True,
677
- direct_edit=direct_edit,
678
- )
679
- ))
680
-
681
- def to_pbo(self) -> ToolDetailsPbo:
682
- """
683
- :return: The ToolDetailsPbo proto object representing this tool.
684
- """
685
- return ToolDetailsPbo(
686
- name=self._name,
687
- description=self._description,
688
- input_configs=self.input_configs,
689
- output_configs=self.output_configs,
690
- output_data_type_name=self._data_type_name,
691
- config_fields=self.config_fields
692
- )
693
-
694
- @abstractmethod
695
- def validate_input(self) -> str | None:
696
- """
697
- Validate the request given to this tool. If the request is validly formatted, this method should return None.
698
- If the request is not valid, this method should return an error message indicating what is wrong with the
699
- request.
700
-
701
- This method should not perform any actual processing of the request. It should only validate the inputs and
702
- configurations provided in the request.
703
-
704
- The request inputs can be accessed using the self.get_input_*() methods.
705
- The request settings can be accessed using the self.get_config_fields() method.
706
- The request itself can be accessed using self.request.
707
-
708
- :return: A tuple containing a boolean indicating whether the request is valid and a message describing the
709
- result of the validation.
710
- """
711
- pass
712
-
713
- def dry_run_output(self) -> list[SapioToolResult]:
714
- """
715
- Provide fixed results for a dry run of this tool. This method should not perform any actual processing of the
716
- request. It should only return example outputs that can be used to test the next tool in the plan.
717
-
718
- The default implementation of this method looks at the testing_example field of each output configuration
719
- and returns a SapioToolResult object based on the content type of the output.
720
-
721
- :return: A list of SapioToolResult objects containing example outputs for this tool. Each result in the list
722
- corresponds to a separate output from the tool.
723
- """
724
- results: list[SapioToolResult] = []
725
- for output, container_type in zip(self.output_configs, self._output_container_types):
726
- config: ToolIoConfigBasePbo = output.base_config
727
- example: ExampleContainerPbo = config.testing_example
728
- content_type: str = config.content_type
729
- match container_type:
730
- case ContainerType.BINARY:
731
- example: bytes = example.binary_example
732
- results.append(BinaryResult(binary_data=[example], content_type=content_type))
733
- case ContainerType.CSV:
734
- example: str = example.text_example
735
- results.append(CsvResult(FileUtil.tokenize_csv(example.encode())[0], content_type=content_type))
736
- case ContainerType.JSON:
737
- # The example may be in the JSONL format instead of plain JSON, so we need to use Pandas to parse
738
- # the example into plain JSON.
739
- example: str = example.text_example
740
- # Format the JSONL in a way that Pandas likes. Collapse everything into a single line, and then
741
- # split it back into multiple lines where each line is a single JSON list or dictionary.
742
- example: str = re.sub("([]}])\s*([\[{])", r"\1\n\2", example.replace("\n", "")).strip()
743
- # Read the JSONL into a Pandas DataFrame and convert it back to plain JSON.
744
- import pandas as pd
745
- with io.StringIO(example) as stream:
746
- example: str = pd.read_json(path_or_buf=stream, lines=True).to_json()
747
- results.append(JsonResult(json_data=[json.loads(example)], content_type=content_type))
748
- case ContainerType.TEXT:
749
- example: str = example.text_example
750
- results.append(TextResult(text_data=[example], content_type=content_type))
751
- return results
752
-
753
- @abstractmethod
754
- def run(self, user: SapioUser) -> list[SapioToolResult]:
755
- """
756
- Execute this tool.
757
-
758
- The request inputs can be accessed using the self.get_input_*() methods.
759
- The request settings can be accessed using the self.get_config_fields() method.
760
- The request itself can be accessed using self.request.
761
-
762
- :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
763
- system.
764
- :return: A list of SapioToolResult objects containing the response data. Each result in the list corresponds to
765
- a separate output from the tool. Field map results do not appear as tool output in the plan manager, instead
766
- appearing as records related to the plan step during the run.
767
- """
768
- pass
769
-
770
- def log_info(self, message: str) -> None:
771
- """
772
- Log an info message for this tool. If verbose logging is enabled, this message will be included in the logs
773
- returned to the caller. Empty/None inputs will not be logged.
774
-
775
- :param message: The message to log.
776
- """
777
- if not message:
778
- return
779
- if self.verbose_logging:
780
- self.logs.append(f"INFO: {self._name}: {message}")
781
- self.logger.info(message)
782
-
783
- def log_warning(self, message: str) -> None:
784
- """
785
- Log a warning message for this tool. This message will be included in the logs returned to the caller.
786
- Empty/None inputs will not be logged.
787
-
788
- :param message: The message to log.
789
- """
790
- if not message:
791
- return
792
- self.logs.append(f"WARNING: {self._name}: {message}")
793
- self.logger.warning(message)
794
-
795
- def log_error(self, message: str) -> None:
796
- """
797
- Log an error message for this tool. This message will be included in the logs returned to the caller.
798
- Empty/None inputs will not be logged.
799
-
800
- :param message: The message to log.
801
- """
802
- if not message:
803
- return
804
- self.logs.append(f"ERROR: {self._name}: {message}")
805
- self.logger.error(message)
806
-
807
- def log_exception(self, message: str, e: Exception) -> None:
808
- """
809
- Log an exception for this tool. This message will be included in the logs returned to the caller.
810
- Empty/None inputs will not be logged.
811
-
812
- :param message: The message to log.
813
- :param e: The exception to log.
814
- """
815
- if not message and not e:
816
- return
817
- self.logs.append(f"EXCEPTION: {self._name}: {message} - {e}")
818
- self.logger.error(f"{message}\n{traceback.format_exc()}")
819
-
820
- def get_input_binary(self, index: int = 0) -> list[bytes]:
821
- """
822
- Get the binary data from the request object.
823
-
824
- :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
825
- :return: The binary data from the request object.
826
- """
827
- return list(self.request.input[index].item_container.binary_container.items)
828
-
829
- def get_input_csv(self, index: int = 0) -> tuple[list[str], list[dict[str, str]]]:
830
- """
831
- Parse the CSV data from the request object.
832
-
833
- :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
834
- :return: A tuple containing the header row and the data rows. The header row is a list of strings representing
835
- the column names, and the data rows are a list of dictionaries where each dictionary represents a row in the
836
- CSV with the column names as keys and the corresponding values as strings.
837
- """
838
- input_data: Sequence[StepInputBatchPbo] = self.request.input
839
- ret_val: list[dict[str, str]] = []
840
- headers: Iterable[str] = input_data[index].item_container.csv_container.header.cells
841
- for row in input_data[index].item_container.csv_container.items:
842
- row_dict: dict[str, str] = {}
843
- for header, value in zip(headers, row.cells):
844
- row_dict[header] = value
845
- ret_val.append(row_dict)
846
- return list(headers), ret_val
847
-
848
- def get_input_json(self, index: int = 0) -> list[list[Any]] | list[dict[str, Any]]:
849
- """
850
- Parse the JSON data from the request object.
851
-
852
- :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
853
- :return: A list of parsed JSON objects. Each entry in the list represents a separate JSON entry from the input.
854
- Depending on this tool, this may be a list of dictionaries or a list of lists.
855
- """
856
- return [json.loads(x) for x in self.request.input[index].item_container.json_container.items]
857
-
858
- def get_input_text(self, index: int = 0) -> list[str]:
859
- """
860
- Parse the text data from the request object.
861
-
862
- :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
863
- :return: A list of text data as strings.
864
- """
865
- return list(self.request.input[index].item_container.text_container.items)
866
-
867
- def get_config_defs(self) -> dict[str, VeloxFieldDefPbo]:
868
- """
869
- Get the config field definitions for this tool.
870
-
871
- :return: A dictionary of field definitions, where the keys are the field names and the values are the
872
- VeloxFieldDefPbo objects representing the field definitions.
873
- """
874
- field_defs: dict[str, VeloxFieldDefPbo] = {}
875
- for field_def in self.to_pbo().config_fields:
876
- field_defs[field_def.data_field_name] = field_def
877
- return field_defs
878
-
879
- def get_config_fields(self) -> dict[str, FieldValue | list[str]]:
880
- """
881
- Get the configuration field values from the request object. If a field is not present in the request,
882
- the default value from the config definition will be returned.
883
-
884
- :return: A dictionary of configuration field names and their values. For multi-select selection list fields,
885
- a list of strings will be returned. For all other field types, the value will match the field type
886
- (bool for boolean fields, float for double fields, int for short, integer, long, and enum fields, and
887
- string for everything else).
888
- """
889
- config_fields: dict[str, Any] = {}
890
- raw_configs: Mapping[str, FieldValuePbo] = self.request.config_field_values
891
- for field_name, field_def in self.get_config_defs().items():
892
- field_value: FieldValue = None
893
- # If the field is present in the request, convert the protobuf value to a Python value.
894
- if field_name in raw_configs:
895
- field_value = ProtobufUtils.field_pbo_to_value(raw_configs[field_name])
896
- # If the field isn't present or is None, use the default value from the field definition.
897
- if field_value is None:
898
- field_value = ProtobufUtils.field_def_pbo_to_default_value(field_def)
899
- # If the field is a multi-select selection list, split the value by commas and strip whitespace.
900
- if field_def.data_field_type == FieldTypePbo.SELECTION and field_def.selection_properties.multi_select:
901
- field_value: list[str] = [x.strip() for x in field_value.split(',') if x.strip()]
902
- config_fields[field_name] = field_value
903
- return config_fields
904
-
905
- @staticmethod
906
- def read_from_json(json_data: list[dict[str, Any]], key: str) -> list[Any]:
907
- """
908
- From a list of dictionaries, return a list of values for the given key from each dictionary. Skips null values.
909
-
910
- :param json_data: The JSON data to read from.
911
- :param key: The key to read the values from.
912
- :return: A list of values corresponding to the given key in the JSON data.
913
- """
914
- ret_val: list[Any] = []
915
- for entry in json_data:
916
- if key in entry:
917
- value = entry[key]
918
- if isinstance(value, list):
919
- ret_val.extend(value)
920
- elif value is not None:
921
- ret_val.append(value)
922
- return ret_val