-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtable.py
More file actions
362 lines (312 loc) · 14 KB
/
table.py
File metadata and controls
362 lines (312 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
"""Tool for building and editing a literature review table.
Intended to support the arxivdigestables task.
Table assumes rows correspond to papers, as in the arxivdigestables task.
Detects and removes orphaned cells when papers are removed.
Highlights missing cells in the table after each operation.
"""
from typing import Annotated, Any, Literal
from inspect_ai.tool import Tool, ToolDef, ToolError, ToolResult, tool
from inspect_ai.util import StoreModel, store_as
from pydantic import BaseModel, Field, RootModel
from shortuuid import uuid
from .submission import get_submission_manager
class Cell(BaseModel):
paper_id: str = Field(..., description="Paper ID for the cell")
value: str = Field(..., description="Cell value")
class Column(BaseModel):
title: str = Field(..., description="Column title")
description: str = Field(..., description="Column description")
values: list[Cell] = Field(
default_factory=list,
description="List of cells, each with paper_id and value",
)
class TableData(BaseModel):
columns: list[Column] = Field(default_factory=list, description="List of columns")
paper_ids: list[str] = Field(
default_factory=list, description="List of paper_ids in the table"
)
missing_cells: dict[str, list[str]] = Field(
default_factory=dict,
description="Mapping from column title to list of paper_ids missing a value",
)
class AddPapersParams(BaseModel):
action: Literal["add_papers"] = "add_papers"
paper_ids: list[str] = Field(..., description="List of paper_id strings to append")
class RemovePapersParams(BaseModel):
action: Literal["remove_papers"] = "remove_papers"
paper_ids: list[str] = Field(..., description="List of paper_id strings to remove")
class AddColumnsParams(BaseModel):
action: Literal["add_columns"] = "add_columns"
columns: list[Column] = Field(
...,
description="List of new columns to append; each may include title, description, and optional initial 'values' dict mapping paper_id→cell.",
)
before_column: str | None = Field(
None,
description=(
"Title of the column before which to insert new columns; "
"if omitted, appends to end"
),
)
class EditColumnValuesParams(BaseModel):
action: Literal["edit_column_values"] = "edit_column_values"
column: str = Field(..., description="Title of the column to update")
updates: list[Cell] = Field(
..., description="List of cells with paper_id and new value"
)
class RemoveColumnsParams(BaseModel):
action: Literal["remove_columns"] = "remove_columns"
target_columns: list[str] = Field(
..., description="List of column titles to remove"
)
class GetTableParams(BaseModel):
action: Literal["get"] = "get"
class UndoParams(BaseModel):
action: Literal["undo"] = "undo"
TableEditorParams = RootModel[
Annotated[
AddPapersParams
| RemovePapersParams
| AddColumnsParams
| EditColumnValuesParams
| RemoveColumnsParams
| GetTableParams
| UndoParams,
Field(discriminator="action"),
]
]
class TableState(StoreModel):
table_state: TableData = Field(default_factory=lambda: TableData())
history: list[str] = Field(default_factory=list)
class TableResponsePayload(BaseModel):
table: TableData
orphaned_cells: list[Cell] = Field(default_factory=list)
@tool
def table_editor(
instance: str | None = uuid(),
history_limit: int = 3,
enable_submission: bool = False,
) -> Tool:
"""Stateful tool to build and edit a table of papers.
Args:
enable_submission: controls whether the "submit" action is available.
Submissions are available via `astabench.tools.submission` with
`has_submission` and `get_submission`.
"""
async def execute(
action: Literal[
"add_papers",
"remove_papers",
"add_columns",
"edit_column_values",
"remove_columns",
"get",
"undo",
"submit",
],
columns: list[Column] | None = None,
paper_ids: list[str] | None = None,
before_column: str | None = None,
remove_columns: list[str] | None = None,
edit_params: EditColumnValuesParams | None = None,
) -> ToolResult:
"""Execute table editing commands.
Args:
action: One of:
- "add_papers": append new rows of paper_ids
- "remove_papers": remove rows of paper_ids
- "add_columns": add new columns
- "edit_column_values": update the values of cells in a column
- "remove_columns": remove columns by title
- "get": retrieve current table state
- "undo": revert to previous state
- "submit": submit the table as the final answer
columns: For "add_columns", list of Column objects. Can be just title/descriptions for outlining
paper_ids: For "add_papers" and "remove_papers", list of paper_id strings
before_column: For "add_columns", title of the column before which to insert new columns (default to end)
remove_columns: For "remove_columns", list of column titles to delete
edit_params: Params for "edit_column_values"
Returns:
A JSON-serializable dict with the current table state and any orphaned cells.
"""
state = store_as(TableState, instance=instance)
# prepare full rollback snapshot for mutating actions
mutating = action not in ("get", "undo")
if mutating:
prior_history = state.history.copy()
prior_table_json = state.table_state.model_dump_json()
state.history.append(prior_table_json)
# enforce maximum history length
if len(state.history) > history_limit:
state.history.pop(0)
# Use a generic variable for params to satisfy mypy across cases
p: Any
# Track orphaned cells removed when papers are deleted
orphaned_cells: list[Cell] = []
# Validate params
if action == "add_columns":
if columns is None:
raise ToolError("Missing columns for add_columns")
p = AddColumnsParams(columns=columns, before_column=before_column)
elif action == "add_papers":
if paper_ids is None:
raise ToolError("Missing paper_ids for add_papers")
p = AddPapersParams(paper_ids=paper_ids)
elif action == "edit_column_values":
if edit_params is None:
raise ToolError("Missing edit_params for edit_column_values")
p = edit_params
elif action == "remove_columns":
if remove_columns is None:
raise ToolError("Missing remove_columns for remove_columns")
p = RemoveColumnsParams(target_columns=remove_columns)
elif action == "remove_papers":
if paper_ids is None:
raise ToolError("Missing paper_ids for remove_papers")
p = RemovePapersParams(paper_ids=paper_ids)
elif action == "undo":
p = UndoParams()
elif action == "get":
p = GetTableParams()
elif action == "submit":
if not enable_submission:
raise ValueError("`submit` action not enabled")
if (
columns is not None
or paper_ids is not None
or before_column is not None
or remove_columns is not None
or edit_params is not None
):
raise ToolError(
"Cannot submit table with pending changes. Please finalize edits and then use 'submit' with no other args."
)
if not state.table_state.columns or not state.table_state.paper_ids:
raise ToolError("Cannot submit empty table")
submission = state.table_state.model_dump_json()
get_submission_manager().write_submission(submission)
return TableResponsePayload(
table=state.table_state,
orphaned_cells=orphaned_cells,
).model_dump_json()
else:
raise ToolError(f"Unknown action {action!r}")
# Dispatch with automatic rollback on any exception
try:
match p:
case AddColumnsParams():
new_cols = []
for col in p.columns:
new_cols.append(col)
# ensure no duplicate titles in the bulk-add payload
titles = [col.title for col in new_cols]
if len(titles) != len(set(titles)):
raise ToolError("Duplicate titles in add_columns payload")
# prevent duplicate column titles
existing_titles = {c.title for c in state.table_state.columns}
for col in new_cols:
if col.title in existing_titles:
raise ToolError(
f"Duplicate column title: {col.title}. If you wanted to edit this column, use the edit_column action instead."
)
existing_titles.add(col.title)
if p.before_column is not None:
idx = next(
(
i
for i, c in enumerate(state.table_state.columns)
if c.title == p.before_column
),
None,
)
if idx is None:
raise ToolError(
f"Column to insert before not found: {p.before_column}"
)
for offset, col in enumerate(new_cols):
state.table_state.columns.insert(idx + offset, col)
else:
state.table_state.columns.extend(new_cols)
case AddPapersParams():
for pid in p.paper_ids:
if pid not in state.table_state.paper_ids:
state.table_state.paper_ids.append(pid)
case EditColumnValuesParams():
# Update the specified column
for col in state.table_state.columns:
if col.title == p.column:
for cell_update in p.updates:
pid, new_val = cell_update.paper_id, cell_update.value
for cell in col.values:
if cell.paper_id == pid:
cell.value = new_val
break
else:
col.values.append(cell_update)
break
else:
raise ToolError(f"Column '{p.column}' not found")
case RemoveColumnsParams():
# Drop columns from definition and from each column's values
state.table_state.columns = [
c
for c in state.table_state.columns
if c.title not in p.target_columns
]
case RemovePapersParams():
# capture cells that will be removed
for col in state.table_state.columns:
for cell in col.values:
if cell.paper_id in p.paper_ids:
orphaned_cells.append(cell)
# Remove paper_ids
state.table_state.paper_ids = [
pid
for pid in state.table_state.paper_ids
if pid not in p.paper_ids
]
# Remove corresponding cell entries
for col in state.table_state.columns:
col.values = [
cell
for cell in col.values
if cell.paper_id not in p.paper_ids
]
case UndoParams():
if not state.history:
raise ToolError("No history to undo.")
last_json = state.history.pop()
state.table_state = TableData.model_validate_json(last_json)
case GetTableParams():
pass
case _:
raise ToolError(f"Unknown action {p.action!r}")
except Exception:
if mutating:
state.history = prior_history
state.table_state = TableData.model_validate_json(prior_table_json)
raise
# compute missing or empty cell values per column
state.table_state.missing_cells = {}
for col in state.table_state.columns:
missing = []
pid_to_cell = {c.paper_id: c for c in col.values}
for pid in state.table_state.paper_ids:
if pid not in pid_to_cell or pid_to_cell[pid].value == "":
missing.append(pid)
state.table_state.missing_cells[col.title] = missing
# return via payload, keep orphaned_cells in payload
payload = TableResponsePayload(
table=state.table_state,
orphaned_cells=orphaned_cells,
)
return payload.model_dump_json()
tool_def = ToolDef(execute, name="table_editor")
if not enable_submission:
# Remove the 'submit' part of the description
lines = tool_def.parameters.properties["action"].description.split("\n")
tool_def.parameters.properties["action"].description = "\n".join(
line for line in lines if not line.startswith('- "submit"')
)
tool_def.parameters.properties["action"].enum.remove("submit")
return tool_def.as_tool()