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