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