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