Skip to content

Service

unique_toolkit.agentic_table.service.AgenticTableService

Provides methods to interact with the Agentic Table.

Attributes:

Name Type Description
#event ChatEvent

The ChatEvent object.

logger Optional[Logger]

The logger object. Defaults to None.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class AgenticTableService:
    """
    Provides methods to interact with the Agentic Table.

    Attributes:
        #event (ChatEvent): The ChatEvent object.
        logger (Optional[logging.Logger]): The logger object. Defaults to None.
    """

    def __init__(
        self,
        user_id: str,
        company_id: str,
        table_id: str,
        event_id: str | None = None,
        logger: logging.Logger = logging.getLogger(__name__),
    ):
        self._event_id = event_id
        self._user_id = user_id
        self._company_id = company_id
        self.table_id = table_id
        self.logger = logger

    async def set_cell(
        self,
        row: int,
        column: int,
        text: str,
        log_entries: list[LogEntry] | None = None,
    ):
        """
        Sets the value of a cell in the Agentic Table.

        Args:
            row (int): The row index.
            column (int): The column index.
            text (str): The text to set.
            log_entries (Optional[list[LogEntry]]): The log entries to set.
        """
        if log_entries is None:
            log_entries_new = []
        else:
            log_entries_new = [
                log_entry.to_sdk_log_entry() for log_entry in log_entries
            ]
        try:
            await AgenticTable.set_cell(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                rowOrder=row,
                columnOrder=column,
                text=text,
                logEntries=log_entries_new,
            )
        except Exception as e:
            self.logger.error(f"Error setting cell {row}, {column}: {e}.")

    async def get_cell(
        self, row: int, column: int, include_row_metadata: bool = True
    ) -> MagicTableCell:
        """
        Gets the value of a cell in the Agentic Table.

        Args:
            row (int): The row index.
            column (int): The column index.
            include_row_metadata (bool): Whether to include the row metadata. Defaults to True.

        Returns:
            MagicTableCell: The MagicTableCell object.

        """
        cell_data = await AgenticTable.get_cell(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            includeRowMetadata=include_row_metadata,  # type: ignore[arg-type]
        )
        return MagicTableCell.model_validate(cell_data)

    async def set_multiple_cells(
        self, cells: list[MagicTableCell], batch_size: int = 4000
    ):
        """
        Sets the values of multiple cells in the Agentic Table.

        Args:
            cells (list[MagicTableCell]): The cells to set sorted by row and column.
            batch_size (int): Number of cells to set in a single request.
        """
        for i in range(0, len(cells), batch_size):
            batch = cells[i : i + batch_size]
            await AgenticTable.set_multiple_cells(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                cells=[
                    SDKAgenticTableCell(
                        rowOrder=cell.row_order,
                        columnOrder=cell.column_order,
                        text=cell.text,
                    )
                    for cell in batch
                ],
            )

    async def set_activity(
        self,
        text: str,
        activity: MagicTableAction,
        status: ActivityStatus = ActivityStatus.IN_PROGRESS,
    ):
        """
        Sets the activity of the Agentic Table.

        Args:
            activity (str): The activity to set.
        """
        await AgenticTable.set_activity(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            activity=activity.value,  # type: ignore[arg-type]
            status=status.value,  # type: ignore[arg-type]
            text=text,
        )

    async def register_agent(self) -> None:
        """
        Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

        Raises:
            LockedAgenticTableError: If the Agentic Table is busy.
        """
        state = await AgenticTable.get_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
        )
        if state == AgenticTableSheetState.IDLE:
            await AgenticTable.update_sheet_state(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                state=AgenticTableSheetState.PROCESSING,
            )
            return
        # If the sheet is not idle, we cannot register the agent
        raise LockedAgenticTableError(
            f"Agentic Table is busy. Cannot register agent {self._event_id or self.table_id}."
        )

    async def deregister_agent(self):
        """
        Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

        Raises:
            LockedAgenticTableError: If the Agentic Table is busy.
        """
        await AgenticTable.update_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            state=AgenticTableSheetState.IDLE,
        )

    async def set_artifact(
        self,
        artifact_type: ArtifactType,
        content_id: str,
        mime_type: str,
        name: str,
    ):
        """Upload/set report files to the Agentic Table.

        Args:
            artifact_type (ArtifactType): The type of artifact to set.
            content_id (str): The content ID of the artifact.
            mime_type (str): The MIME type of the artifact.
            name (str): The name of the artifact.
        """
        await AgenticTable.set_artifact(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            artifactType=artifact_type.value,
            contentId=content_id,
            mimeType=mime_type,
            name=name,
        )

    @deprecated("Use set_column_style instead.")
    async def set_column_width(self, column: int, width: int):
        await self.set_column_style(column=column, width=width)

    async def set_column_style(
        self,
        column: int,
        width: int | None = None,
        cell_renderer: CellRendererTypes | None = None,
        filter: FilterTypes | None = None,
        editable: bool | None = None,
    ):
        """
        Sets the style of a column in the Agentic Table.

        Args:
            column (int): The column index.
            width (int | None, optional): The width of the column. Defaults to None.
            cell_renderer (CellRenderer | None, optional): The cell renderer of the column. Defaults to None.
            filter (FilterComponents | None, optional): The filter of the column. Defaults to None.
            editable (bool | None, optional): Whether the column is editable. Defaults to None.

        Raises:
            Exception: If the column style is not set.
        """
        # Convert the input to the correct format
        params = {}
        if width is not None:
            params["columnWidth"] = width
        if cell_renderer is not None:
            params["cellRenderer"] = cell_renderer.value
        if filter is not None:
            params["filter"] = filter.value
        if editable is not None:
            params["editable"] = editable
        status, message = await AgenticTable.set_column_metadata(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            columnOrder=column,
            **params,
        )
        if status:
            return
        raise Exception(message)

    async def get_num_rows(self) -> int:
        """
        Gets the number of rows in the Agentic Table.

        Returns:
            int: The number of rows in the Agentic Table.
        """
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeRowCount=True,
            includeCells=False,
            includeLogHistory=False,
        )
        return sheet_info["magicTableRowCount"]

    async def get_sheet(
        self,
        start_row: int = 0,
        end_row: int | None = None,
        batch_size: int = 100,
        include_log_history: bool = False,
        include_cell_meta_data: bool = False,
        include_row_metadata: bool = False,
    ) -> MagicTableSheet:
        """
        Gets the sheet data from the Agentic Table paginated by batch_size.

        Args:
            start_row (int): The start row (inclusive).
            end_row (int | None): The end row (not inclusive).
            batch_size (int): The batch size.
            include_log_history (bool): Whether to include the log history.
            include_cell_meta_data (bool): Whether to include the cell metadata (renderer, selection, agreement status).
            include_row_metadata (bool): Whether to include the row metadata (key value pairs).
        Returns:
            MagicTableSheet: The sheet data.
        """
        # Find the total number of rows
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeRowCount=True,
            includeCells=False,
            includeLogHistory=False,
            includeCellMetaData=False,
        )
        total_rows = sheet_info["magicTableRowCount"]
        if end_row is None or end_row > total_rows:
            end_row = total_rows
        if start_row > end_row:
            raise Exception("Start row is greater than end row")
        if start_row < 0 or end_row < 0:
            raise Exception("Start row or end row is negative")

        # Get the cells
        cells = []
        for row in range(start_row, end_row, batch_size):
            end_row_batch = min(row + batch_size, end_row)
            sheet_partial = await AgenticTable.get_sheet_data(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                includeCells=True,
                includeLogHistory=include_log_history,
                includeRowCount=False,
                includeCellMetaData=include_cell_meta_data,  # renderer, selection, agreement status
                startRow=row,
                endRow=end_row_batch - 1,
            )
            if "magicTableCells" in sheet_partial:
                if include_row_metadata:
                    # If include_row_metadata is true, we need to get the row metadata for each cell.
                    row_metadata_map = {}
                    # TODO: @thea-unique This routine is not efficient and would be nice if we had this data passed on in get_sheet_data.
                    for cell in sheet_partial["magicTableCells"]:
                        row_order = cell.get("rowOrder")  # type: ignore[assignment]
                        if row_order is not None and row_order not in row_metadata_map:
                            column_order = cell.get("columnOrder")  # type: ignore[assignment]
                            self.logger.info(
                                f"Getting row metadata for cell {row_order}, {column_order}"
                            )
                            cell_with_row_metadata = await self.get_cell(
                                row_order,
                                column_order,  # type: ignore[arg-type]
                            )
                            if cell_with_row_metadata.row_metadata:
                                print(cell_with_row_metadata.row_metadata)
                                row_metadata_map[cell_with_row_metadata.row_order] = (
                                    cell_with_row_metadata.row_metadata
                                )
                                cell["rowMetadata"] = (  # type: ignore[assignment]
                                    cell_with_row_metadata.row_metadata
                                )
                    # Assign row_metadata to all cells
                    for cell in sheet_partial["magicTableCells"]:
                        row_order = cell.get("rowOrder")  # type: ignore[assignment]
                        if row_order is not None and row_order in row_metadata_map:
                            cell["rowMetadata"] = row_metadata_map[  # type: ignore[assignment]
                                row_order
                            ]

                cells.extend(sheet_partial["magicTableCells"])

        sheet_info["magicTableCells"] = cells
        return MagicTableSheet.model_validate(sheet_info)

    async def get_sheet_metadata(self) -> list[RowMetadataEntry]:
        """
        Gets the sheet metadata from the Agentic Table.

        Returns:
            list[RowMetadataEntry]: The sheet metadata.
        """
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeSheetMetadata=True,  # type: ignore[arg-type]
        )
        return [
            RowMetadataEntry.model_validate(metadata)
            for metadata in sheet_info["magicTableSheetMetadata"]
        ]

    async def set_cell_metadata(
        self,
        row: int,
        column: int,
        selected: bool | None = None,
        selection_method: SelectionMethod | None = None,
        agreement_status: AgreementStatus | None = None,
    ) -> None:
        """
        Sets the cell metadata for the Agentic Table.
        NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

        Args:
            row (int): The row index.
            column (int): The column index.
            selected (bool | None): Whether the cell is selected.
            selection_method (SelectionMethod | None): The method of selection.
            agreement_status (AgreementStatus | None): The agreement status.
        """
        params = {}
        if selected is not None:
            params["selected"] = selected
        if selection_method is not None:
            params["selectionMethod"] = selection_method
        if agreement_status is not None:
            params["agreementStatus"] = agreement_status
        result = await AgenticTable.set_cell_metadata(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            **params,
        )
        if result["status"]:  # type: ignore
            return
        raise Exception(result["message"])  # type: ignore

    async def update_row_verification_status(
        self,
        row_orders: list[int],
        status: RowVerificationStatus,
    ):
        """Update the verification status of multiple rows at once.

        Args:
            row_orders (list[int]): The row indexes to update.
            status (RowVerificationStatus): The verification status to set.
        """
        await AgenticTable.bulk_update_status(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrders=row_orders,
            status=status,
        )

deregister_agent() async

Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

Raises:

Type Description
LockedAgenticTableError

If the Agentic Table is busy.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def deregister_agent(self):
    """
    Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

    Raises:
        LockedAgenticTableError: If the Agentic Table is busy.
    """
    await AgenticTable.update_sheet_state(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        state=AgenticTableSheetState.IDLE,
    )

get_cell(row, column, include_row_metadata=True) async

Gets the value of a cell in the Agentic Table.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
include_row_metadata bool

Whether to include the row metadata. Defaults to True.

True

Returns:

Name Type Description
MagicTableCell MagicTableCell

The MagicTableCell object.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def get_cell(
    self, row: int, column: int, include_row_metadata: bool = True
) -> MagicTableCell:
    """
    Gets the value of a cell in the Agentic Table.

    Args:
        row (int): The row index.
        column (int): The column index.
        include_row_metadata (bool): Whether to include the row metadata. Defaults to True.

    Returns:
        MagicTableCell: The MagicTableCell object.

    """
    cell_data = await AgenticTable.get_cell(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrder=row,
        columnOrder=column,
        includeRowMetadata=include_row_metadata,  # type: ignore[arg-type]
    )
    return MagicTableCell.model_validate(cell_data)

get_num_rows() async

Gets the number of rows in the Agentic Table.

Returns:

Name Type Description
int int

The number of rows in the Agentic Table.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def get_num_rows(self) -> int:
    """
    Gets the number of rows in the Agentic Table.

    Returns:
        int: The number of rows in the Agentic Table.
    """
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeRowCount=True,
        includeCells=False,
        includeLogHistory=False,
    )
    return sheet_info["magicTableRowCount"]

get_sheet(start_row=0, end_row=None, batch_size=100, include_log_history=False, include_cell_meta_data=False, include_row_metadata=False) async

Gets the sheet data from the Agentic Table paginated by batch_size.

Parameters:

Name Type Description Default
start_row int

The start row (inclusive).

0
end_row int | None

The end row (not inclusive).

None
batch_size int

The batch size.

100
include_log_history bool

Whether to include the log history.

False
include_cell_meta_data bool

Whether to include the cell metadata (renderer, selection, agreement status).

False
include_row_metadata bool

Whether to include the row metadata (key value pairs).

False
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def get_sheet(
    self,
    start_row: int = 0,
    end_row: int | None = None,
    batch_size: int = 100,
    include_log_history: bool = False,
    include_cell_meta_data: bool = False,
    include_row_metadata: bool = False,
) -> MagicTableSheet:
    """
    Gets the sheet data from the Agentic Table paginated by batch_size.

    Args:
        start_row (int): The start row (inclusive).
        end_row (int | None): The end row (not inclusive).
        batch_size (int): The batch size.
        include_log_history (bool): Whether to include the log history.
        include_cell_meta_data (bool): Whether to include the cell metadata (renderer, selection, agreement status).
        include_row_metadata (bool): Whether to include the row metadata (key value pairs).
    Returns:
        MagicTableSheet: The sheet data.
    """
    # Find the total number of rows
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeRowCount=True,
        includeCells=False,
        includeLogHistory=False,
        includeCellMetaData=False,
    )
    total_rows = sheet_info["magicTableRowCount"]
    if end_row is None or end_row > total_rows:
        end_row = total_rows
    if start_row > end_row:
        raise Exception("Start row is greater than end row")
    if start_row < 0 or end_row < 0:
        raise Exception("Start row or end row is negative")

    # Get the cells
    cells = []
    for row in range(start_row, end_row, batch_size):
        end_row_batch = min(row + batch_size, end_row)
        sheet_partial = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeCells=True,
            includeLogHistory=include_log_history,
            includeRowCount=False,
            includeCellMetaData=include_cell_meta_data,  # renderer, selection, agreement status
            startRow=row,
            endRow=end_row_batch - 1,
        )
        if "magicTableCells" in sheet_partial:
            if include_row_metadata:
                # If include_row_metadata is true, we need to get the row metadata for each cell.
                row_metadata_map = {}
                # TODO: @thea-unique This routine is not efficient and would be nice if we had this data passed on in get_sheet_data.
                for cell in sheet_partial["magicTableCells"]:
                    row_order = cell.get("rowOrder")  # type: ignore[assignment]
                    if row_order is not None and row_order not in row_metadata_map:
                        column_order = cell.get("columnOrder")  # type: ignore[assignment]
                        self.logger.info(
                            f"Getting row metadata for cell {row_order}, {column_order}"
                        )
                        cell_with_row_metadata = await self.get_cell(
                            row_order,
                            column_order,  # type: ignore[arg-type]
                        )
                        if cell_with_row_metadata.row_metadata:
                            print(cell_with_row_metadata.row_metadata)
                            row_metadata_map[cell_with_row_metadata.row_order] = (
                                cell_with_row_metadata.row_metadata
                            )
                            cell["rowMetadata"] = (  # type: ignore[assignment]
                                cell_with_row_metadata.row_metadata
                            )
                # Assign row_metadata to all cells
                for cell in sheet_partial["magicTableCells"]:
                    row_order = cell.get("rowOrder")  # type: ignore[assignment]
                    if row_order is not None and row_order in row_metadata_map:
                        cell["rowMetadata"] = row_metadata_map[  # type: ignore[assignment]
                            row_order
                        ]

            cells.extend(sheet_partial["magicTableCells"])

    sheet_info["magicTableCells"] = cells
    return MagicTableSheet.model_validate(sheet_info)

get_sheet_metadata() async

Gets the sheet metadata from the Agentic Table.

Returns:

Type Description
list[RowMetadataEntry]

list[RowMetadataEntry]: The sheet metadata.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def get_sheet_metadata(self) -> list[RowMetadataEntry]:
    """
    Gets the sheet metadata from the Agentic Table.

    Returns:
        list[RowMetadataEntry]: The sheet metadata.
    """
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeSheetMetadata=True,  # type: ignore[arg-type]
    )
    return [
        RowMetadataEntry.model_validate(metadata)
        for metadata in sheet_info["magicTableSheetMetadata"]
    ]

register_agent() async

Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

Raises:

Type Description
LockedAgenticTableError

If the Agentic Table is busy.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def register_agent(self) -> None:
    """
    Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

    Raises:
        LockedAgenticTableError: If the Agentic Table is busy.
    """
    state = await AgenticTable.get_sheet_state(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
    )
    if state == AgenticTableSheetState.IDLE:
        await AgenticTable.update_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            state=AgenticTableSheetState.PROCESSING,
        )
        return
    # If the sheet is not idle, we cannot register the agent
    raise LockedAgenticTableError(
        f"Agentic Table is busy. Cannot register agent {self._event_id or self.table_id}."
    )

set_activity(text, activity, status=ActivityStatus.IN_PROGRESS) async

Sets the activity of the Agentic Table.

Parameters:

Name Type Description Default
activity str

The activity to set.

required
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_activity(
    self,
    text: str,
    activity: MagicTableAction,
    status: ActivityStatus = ActivityStatus.IN_PROGRESS,
):
    """
    Sets the activity of the Agentic Table.

    Args:
        activity (str): The activity to set.
    """
    await AgenticTable.set_activity(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        activity=activity.value,  # type: ignore[arg-type]
        status=status.value,  # type: ignore[arg-type]
        text=text,
    )

set_artifact(artifact_type, content_id, mime_type, name) async

Upload/set report files to the Agentic Table.

Parameters:

Name Type Description Default
artifact_type ArtifactType

The type of artifact to set.

required
content_id str

The content ID of the artifact.

required
mime_type str

The MIME type of the artifact.

required
name str

The name of the artifact.

required
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_artifact(
    self,
    artifact_type: ArtifactType,
    content_id: str,
    mime_type: str,
    name: str,
):
    """Upload/set report files to the Agentic Table.

    Args:
        artifact_type (ArtifactType): The type of artifact to set.
        content_id (str): The content ID of the artifact.
        mime_type (str): The MIME type of the artifact.
        name (str): The name of the artifact.
    """
    await AgenticTable.set_artifact(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        artifactType=artifact_type.value,
        contentId=content_id,
        mimeType=mime_type,
        name=name,
    )

set_cell(row, column, text, log_entries=None) async

Sets the value of a cell in the Agentic Table.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
text str

The text to set.

required
log_entries Optional[list[LogEntry]]

The log entries to set.

None
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_cell(
    self,
    row: int,
    column: int,
    text: str,
    log_entries: list[LogEntry] | None = None,
):
    """
    Sets the value of a cell in the Agentic Table.

    Args:
        row (int): The row index.
        column (int): The column index.
        text (str): The text to set.
        log_entries (Optional[list[LogEntry]]): The log entries to set.
    """
    if log_entries is None:
        log_entries_new = []
    else:
        log_entries_new = [
            log_entry.to_sdk_log_entry() for log_entry in log_entries
        ]
    try:
        await AgenticTable.set_cell(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            text=text,
            logEntries=log_entries_new,
        )
    except Exception as e:
        self.logger.error(f"Error setting cell {row}, {column}: {e}.")

set_cell_metadata(row, column, selected=None, selection_method=None, agreement_status=None) async

Sets the cell metadata for the Agentic Table. NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
selected bool | None

Whether the cell is selected.

None
selection_method SelectionMethod | None

The method of selection.

None
agreement_status AgreementStatus | None

The agreement status.

None
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_cell_metadata(
    self,
    row: int,
    column: int,
    selected: bool | None = None,
    selection_method: SelectionMethod | None = None,
    agreement_status: AgreementStatus | None = None,
) -> None:
    """
    Sets the cell metadata for the Agentic Table.
    NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

    Args:
        row (int): The row index.
        column (int): The column index.
        selected (bool | None): Whether the cell is selected.
        selection_method (SelectionMethod | None): The method of selection.
        agreement_status (AgreementStatus | None): The agreement status.
    """
    params = {}
    if selected is not None:
        params["selected"] = selected
    if selection_method is not None:
        params["selectionMethod"] = selection_method
    if agreement_status is not None:
        params["agreementStatus"] = agreement_status
    result = await AgenticTable.set_cell_metadata(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrder=row,
        columnOrder=column,
        **params,
    )
    if result["status"]:  # type: ignore
        return
    raise Exception(result["message"])  # type: ignore

set_column_style(column, width=None, cell_renderer=None, filter=None, editable=None) async

Sets the style of a column in the Agentic Table.

Parameters:

Name Type Description Default
column int

The column index.

required
width int | None

The width of the column. Defaults to None.

None
cell_renderer CellRenderer | None

The cell renderer of the column. Defaults to None.

None
filter FilterComponents | None

The filter of the column. Defaults to None.

None
editable bool | None

Whether the column is editable. Defaults to None.

None

Raises:

Type Description
Exception

If the column style is not set.

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_column_style(
    self,
    column: int,
    width: int | None = None,
    cell_renderer: CellRendererTypes | None = None,
    filter: FilterTypes | None = None,
    editable: bool | None = None,
):
    """
    Sets the style of a column in the Agentic Table.

    Args:
        column (int): The column index.
        width (int | None, optional): The width of the column. Defaults to None.
        cell_renderer (CellRenderer | None, optional): The cell renderer of the column. Defaults to None.
        filter (FilterComponents | None, optional): The filter of the column. Defaults to None.
        editable (bool | None, optional): Whether the column is editable. Defaults to None.

    Raises:
        Exception: If the column style is not set.
    """
    # Convert the input to the correct format
    params = {}
    if width is not None:
        params["columnWidth"] = width
    if cell_renderer is not None:
        params["cellRenderer"] = cell_renderer.value
    if filter is not None:
        params["filter"] = filter.value
    if editable is not None:
        params["editable"] = editable
    status, message = await AgenticTable.set_column_metadata(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        columnOrder=column,
        **params,
    )
    if status:
        return
    raise Exception(message)

set_multiple_cells(cells, batch_size=4000) async

Sets the values of multiple cells in the Agentic Table.

Parameters:

Name Type Description Default
cells list[MagicTableCell]

The cells to set sorted by row and column.

required
batch_size int

Number of cells to set in a single request.

4000
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def set_multiple_cells(
    self, cells: list[MagicTableCell], batch_size: int = 4000
):
    """
    Sets the values of multiple cells in the Agentic Table.

    Args:
        cells (list[MagicTableCell]): The cells to set sorted by row and column.
        batch_size (int): Number of cells to set in a single request.
    """
    for i in range(0, len(cells), batch_size):
        batch = cells[i : i + batch_size]
        await AgenticTable.set_multiple_cells(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            cells=[
                SDKAgenticTableCell(
                    rowOrder=cell.row_order,
                    columnOrder=cell.column_order,
                    text=cell.text,
                )
                for cell in batch
            ],
        )

update_row_verification_status(row_orders, status) async

Update the verification status of multiple rows at once.

Parameters:

Name Type Description Default
row_orders list[int]

The row indexes to update.

required
status RowVerificationStatus

The verification status to set.

required
Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
async def update_row_verification_status(
    self,
    row_orders: list[int],
    status: RowVerificationStatus,
):
    """Update the verification status of multiple rows at once.

    Args:
        row_orders (list[int]): The row indexes to update.
        status (RowVerificationStatus): The verification status to set.
    """
    await AgenticTable.bulk_update_status(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrders=row_orders,
        status=status,
    )

Schemas

Event

The primary event type is MagicTableEvent.

unique_toolkit.agentic_table.schemas.MagicTableEvent pydantic-model

Bases: ChatEvent

Fields:

  • id (str)
  • user_id (str)
  • company_id (str)
  • created_at (Optional[int])
  • version (Optional[str])
Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableEvent(ChatEvent):
    event: MagicTableEventTypes  # type: ignore[assignment]
    payload: MagicTablePayloadTypes  # type: ignore[assignment]

Event Payload Schemas

All event payloads inherit from the MagicTableBasePayload schema.

unique_toolkit.agentic_table.schemas.MagicTableBasePayload pydantic-model

Bases: BaseModel, Generic[A, T]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableBasePayload(BaseModel, Generic[A, T]):
    model_config = get_configuration_dict()
    name: str = Field(description="The name of the module")
    sheet_name: str

    action: A
    chat_id: str
    assistant_id: str
    table_id: str
    user_message: ChatEventUserMessage = Field(
        default=ChatEventUserMessage(
            id="", text="", original_text="", created_at="", language=""
        )
    )
    assistant_message: ChatEventAssistantMessage = Field(
        default=ChatEventAssistantMessage(id="", created_at="")
    )
    configuration: dict[str, Any] = {}
    metadata: T
    metadata_filter: dict[str, Any] | None = None

The following payload schemas correspond to the events listed above:

unique_toolkit.agentic_table.schemas.MagicTableUpdateCellPayload pydantic-model

Bases: MagicTableBasePayload[Literal[UPDATE_CELL], DDMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableUpdateCellPayload(
    MagicTableBasePayload[Literal[MagicTableAction.UPDATE_CELL], DDMetadata]
):
    column_order: int
    row_order: int
    data: str

unique_toolkit.agentic_table.schemas.MagicTableAddMetadataPayload pydantic-model

Bases: MagicTableBasePayload[Literal[ADD_META_DATA], DDMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableAddMetadataPayload(
    MagicTableBasePayload[Literal[MagicTableAction.ADD_META_DATA], DDMetadata]
): ...

unique_toolkit.agentic_table.schemas.MagicTableGenerateArtifactPayload pydantic-model

Bases: MagicTableBasePayload[Literal[GENERATE_ARTIFACT], BaseMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableGenerateArtifactPayload(
    MagicTableBasePayload[Literal[MagicTableAction.GENERATE_ARTIFACT], BaseMetadata]
):
    data: ArtifactData

unique_toolkit.agentic_table.schemas.MagicTableSheetCompletedPayload pydantic-model

Bases: MagicTableBasePayload[Literal[SHEET_COMPLETED], SheetCompletedMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableSheetCompletedPayload(
    MagicTableBasePayload[
        Literal[MagicTableAction.SHEET_COMPLETED], SheetCompletedMetadata
    ]
): ...

unique_toolkit.agentic_table.schemas.MagicTableLibrarySheetRowVerifiedPayload pydantic-model

Bases: MagicTableBasePayload[Literal[LIBRARY_SHEET_ROW_VERIFIED], LibrarySheetRowVerifiedMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableLibrarySheetRowVerifiedPayload(
    MagicTableBasePayload[
        Literal[MagicTableAction.LIBRARY_SHEET_ROW_VERIFIED],
        LibrarySheetRowVerifiedMetadata,
    ]
): ...

unique_toolkit.agentic_table.schemas.MagicTableSheetCreatedPayload pydantic-model

Bases: MagicTableBasePayload[Literal[SHEET_CREATED], SheetCreatedMetadata]

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableSheetCreatedPayload(
    MagicTableBasePayload[Literal[MagicTableAction.SHEET_CREATED], SheetCreatedMetadata]
): ...

Supporting Schemas

unique_toolkit.agentic_table.schemas.BaseMetadata pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class BaseMetadata(BaseModel):
    model_config = get_configuration_dict()

    sheet_type: SheetType = Field(
        description="The type of the sheet.",
        default=SheetType.DEFAULT,
    )

    additional_sheet_information: dict[str, Any] = Field(
        default_factory=dict, description="Additional information for the sheet"
    )

    @field_validator("additional_sheet_information", mode="before")
    @classmethod
    def normalize_additional_sheet_information(cls, v):
        if v is None:
            return {}
        return v

unique_toolkit.agentic_table.schemas.DDMetadata pydantic-model

Bases: BaseMetadata

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class DDMetadata(BaseMetadata):
    model_config = get_configuration_dict()

    question_file_ids: list[str] = Field(
        default_factory=list, description="The IDs of the question files"
    )
    source_file_ids: list[str] = Field(
        default_factory=list, description="The IDs of the source files"
    )
    question_texts: list[str] = Field(
        default_factory=list, description="The texts of the questions"
    )
    context: str = Field(default="", description="The context text for the table.")

    @field_validator("context", mode="before")
    @classmethod
    def normalize_context(cls, v):
        if v is None:
            return ""
        return v

unique_toolkit.agentic_table.schemas.SheetCompletedMetadata pydantic-model

Bases: BaseMetadata

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class SheetCompletedMetadata(BaseMetadata):
    model_config = get_configuration_dict()
    sheet_id: str = Field(description="The ID of the sheet that was completed.")
    library_sheet_id: str = Field(
        description="The ID of the library corresponding to the sheet."
    )
    context: str = Field(default="", description="The context text for the table.")

    @field_validator("context", mode="before")
    @classmethod
    def normalize_context(cls, v):
        if v is None:
            return ""
        return v

unique_toolkit.agentic_table.schemas.SheetCreatedMetadata pydantic-model

Bases: BaseMetadata

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class SheetCreatedMetadata(BaseMetadata): ...

unique_toolkit.agentic_table.schemas.LibrarySheetRowVerifiedMetadata pydantic-model

Bases: BaseMetadata

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class LibrarySheetRowVerifiedMetadata(BaseMetadata):
    model_config = get_configuration_dict()
    row_order: int = Field(description="The row index of the row that was verified.")

unique_toolkit.agentic_table.schemas.ArtifactData pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class ArtifactData(BaseModel):
    model_config = get_configuration_dict()
    artifact_type: ArtifactType

unique_toolkit.agentic_table.schemas.ArtifactType

Bases: StrEnum

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class ArtifactType(StrEnum):
    QUESTIONS = "QUESTIONS"
    FULL_REPORT = "FULL_REPORT"
    AGENTIC_REPORT = "AGENTIC_REPORT"

unique_toolkit.agentic_table.schemas.MagicTableCell pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableCell(BaseModel):
    model_config = get_configuration_dict()
    sheet_id: str
    row_order: int = Field(description="The row index of the cell.")
    column_order: int = Field(description="The column index of the cell.")
    row_locked: bool = Field(default=False, description="Lock status of the row.")
    text: str
    log_entries: list[LogEntry] = Field(
        default_factory=list, description="The log entries for the cell"
    )
    meta_data: MagicTableCellMetaData | None = Field(
        default=None, description="The metadata for the cell"
    )
    row_metadata: list[RowMetadataEntry] = Field(
        default_factory=list,
        description="The metadata (key value pairs)for the rows.",
    )

unique_toolkit.agentic_table.schemas.MagicTableSheet pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class MagicTableSheet(BaseModel):
    model_config = get_configuration_dict()
    sheet_id: str
    name: str
    state: AgenticTableSheetState
    total_number_of_rows: int = Field(
        default=0,
        description="The total number of rows in the sheet",
        alias="magicTableRowCount",
    )
    chat_id: str
    created_by: str
    company_id: str
    created_at: str
    magic_table_cells: list[MagicTableCell] = Field(
        default_factory=list, description="The cells in the sheet"
    )
    magic_table_sheet_metadata: list[RowMetadataEntry] = Field(
        default_factory=list, description="The metadata for the sheet"
    )

unique_toolkit.agentic_table.schemas.LogEntry pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class LogEntry(BaseModel):
    model_config = get_configuration_dict()

    text: str
    created_at: str
    actor_type: LanguageModelMessageRole
    message_id: str | None = None
    details: LogDetail | None = Field(
        default=None, description="The details of the log entry"
    )

    @field_validator("actor_type", mode="before")
    @classmethod
    def normalize_actor_type(cls, v):
        if isinstance(v, str):
            return v.lower()
        return v

    def to_sdk_log_entry(self) -> SDKLogEntry:
        params: dict[str, Any] = {
            "text": self.text,
            "createdAt": self.created_at,
            "actorType": self.actor_type.value.upper(),
        }
        if self.details:
            params["details"] = self.details.to_sdk_log_detail()

        return SDKLogEntry(**params)

unique_toolkit.agentic_table.schemas.LogDetail pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class LogDetail(BaseModel):
    model_config = get_configuration_dict()
    llm_request: LanguageModelMessages | None = Field(
        default=None, description="The LLM request for the log detail"
    )

    def to_sdk_log_detail(self) -> SDKLogDetail:
        llm_request = None
        if self.llm_request:
            llm_request = self.llm_request.model_dump()
        return SDKLogDetail(llmRequest=llm_request)

unique_toolkit.agentic_table.schemas.RowMetadataEntry pydantic-model

Bases: BaseModel

Source code in unique_toolkit/unique_toolkit/agentic_table/schemas.py
class RowMetadataEntry(BaseModel):
    model_config = get_configuration_dict()
    id: str = Field(description="The ID of the metadata")
    key: str = Field(description="The key of the metadata")
    value: str = Field(description="The value of the metadata")
    exact_filter: bool = Field(
        default=False,
        description="Whether the metadata is to be used for strict filtering",
    )

Exceptions

unique_toolkit.agentic_table.service.LockedAgenticTableError

Bases: Exception

Source code in unique_toolkit/unique_toolkit/agentic_table/service.py
class LockedAgenticTableError(Exception):
    pass