feat: query S3 table files from the AI session

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-30 01:24:28 -08:00
co-authored by Claude Opus 5.5
parent d1d7f3d355
commit 7fb13a8628
4 changed files with 420 additions and 18 deletions
@@ -2731,6 +2731,99 @@
},
"read_only": true
},
{
"name": "query_s3_table",
"description": "Rows of a table file in the workspace's object storage: CSV, TSV, Parquet, or newline-delimited JSON (.jsonl, .ndjson). The server filters, searches, sorts and pages, so filter here rather than reading rows to find a value. Returns the columns and their types, the rows as objects, and `more` with the offset of the next page when more rows match.",
"parameters": {
"type": "object",
"properties": {
"s3": {
"description": "Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.",
"type": "string"
},
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
},
"columns": {
"description": "Columns to return, in this order. Omit for every column.",
"type": "array",
"items": {
"type": "string"
}
},
"search": {
"description": "Keep the rows where any column contains this text, ignoring case.",
"type": "string"
},
"filters": {
"description": "Keep the rows that match every filter, by column name. A number column takes a number or a comparison such as `\">=10\"` or `\"!=0\"`; a boolean column takes true or false; a text column takes a substring, matched ignoring case, or `\"=value\"` for an exact match.",
"type": "object",
"propertyNames": {
"type": "string"
},
"additionalProperties": {
"anyOf": [
{
"type": "string"
},
{
"type": "number"
},
{
"type": "boolean"
}
]
}
},
"sort": {
"description": "Sort the matching rows by one column, ascending unless `desc` is true.",
"type": "object",
"properties": {
"column": {
"type": "string"
},
"desc": {
"type": "boolean"
}
},
"required": [
"column"
],
"additionalProperties": false
},
"offset": {
"description": "Matching rows to skip: pass `more.offset` from the previous call for the next page.",
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
},
"limit": {
"description": "Max number of rows to return. Defaults to 50.",
"type": "integer",
"minimum": 1,
"maximum": 500
},
"count": {
"description": "Also return `matching_rows`, the number of rows that match.",
"type": "boolean"
},
"csv_separator": {
"description": "Column separator of a CSV or TSV file. Detected when omitted.",
"type": "string"
},
"csv_has_header": {
"description": "Whether the first line of a CSV or TSV file names the columns. Defaults to true.",
"type": "boolean"
}
},
"required": [
"s3"
],
"additionalProperties": false
},
"read_only": true
},
{
"name": "delete_s3_file",
"description": "Delete one file from the workspace's object storage. It cannot be undone: call it only when the user asked for that file to be deleted.",
@@ -190,6 +190,7 @@ const OPEN_WORLD: &[&str] = &[
"get_db_schema",
"list_s3_files",
"read_s3_file",
"query_s3_table",
"delete_s3_file",
"move_s3_file",
];
@@ -6,11 +6,12 @@ use serde_json::{json, Map, Value};
use super::data::with_query;
use super::workspace::path_enc;
use super::{array, opt_str_arg, pretty, str_arg, Ctx, ToolResult};
use super::{array, bool_arg, opt_str_arg, pretty, str_arg, Ctx, ToolResult};
pub(super) const TOOLS: &[&str] = &[
"list_s3_files",
"read_s3_file",
"query_s3_table",
"delete_s3_file",
"move_s3_file",
];
@@ -19,6 +20,7 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult
let result = match name {
"list_s3_files" => list_s3_files(ctx, args).await,
"read_s3_file" => read_s3_file(ctx, args).await,
"query_s3_table" => query_s3_table(ctx, args).await,
"delete_s3_file" => delete_s3_file(ctx, args).await,
"move_s3_file" => move_s3_file(ctx, args).await,
_ => unreachable!("{name} is not a storage tool"),
@@ -46,6 +48,9 @@ const PARQUET_PREVIEW_ROWS: usize = 50;
/// The CSV preview endpoint parses at most this many rows, whatever length it is asked.
const CSV_PREVIEW_ROWS: usize = 20;
const MAX_CELL_CHARS: usize = 1000;
const DEFAULT_QUERY_ROWS: u64 = 50;
const MAX_QUERY_ROWS: u64 = 500;
const QUERY_HINT: &str = "Filter, sort or page it with query_s3_table.";
/// Anthropic refuses an image whose base64 data passes 5 MB, and the server has no image
/// library to downscale with.
const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024 / 4 * 3;
@@ -202,12 +207,16 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
],
))
.await?;
fit_parquet(
let rows = array(preview.get("rows"));
fit_table(
&mut out,
array(preview.get("columns")),
array(preview.get("column_types")),
array(preview.get("rows")),
rows,
0,
rows.len() == PARQUET_PREVIEW_ROWS,
);
add_note(&mut out, QUERY_HINT);
} else if is_image_key(key) {
if size > MAX_IMAGE_BYTES {
out.insert("image".into(), "not attached: larger than 3.75 MB".into());
@@ -250,6 +259,9 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let csv_cut =
preview["content_type"] == "Csv" && content.lines().count() > CSV_PREVIEW_ROWS;
fit_text(&mut out, content, length < size, csv_cut);
if table_endpoint(key).is_some() {
add_note(&mut out, QUERY_HINT);
}
}
None => {
out.insert("preview_unavailable".into(), preview["msg"].clone());
@@ -279,6 +291,175 @@ async fn text_preview(
.await
}
/// The endpoint that reads a table file, by its extension. Both run DataFusion, which
/// filters, sorts and pages on the server; the CSV one sniffs the delimiter and reads
/// newline-delimited JSON by extension.
fn table_endpoint(key: &str) -> Option<&'static str> {
match key.rsplit_once('.')?.1.to_lowercase().as_str() {
"parquet" => Some("load_parquet_preview"),
"csv" | "tsv" | "jsonl" | "ndjson" => Some("load_csv_preview"),
_ => None,
}
}
async fn query_s3_table(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let key = str_arg(args, "s3")?;
let storage = storage_arg(args);
let endpoint = table_endpoint(key).ok_or_else(|| {
format!("{key} is not a table: query_s3_table reads .csv, .tsv, .parquet, .jsonl and .ndjson files. Read it with read_s3_file.")
})?;
let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(0);
let limit = args
.get("limit")
.and_then(Value::as_u64)
.unwrap_or(DEFAULT_QUERY_ROWS)
.clamp(1, MAX_QUERY_ROWS);
let selection = selection_params(args, storage)?;
let mut params = selection.clone();
if let Some(sort) = args.get("sort").filter(|s| !s.is_null()) {
params.push(("sort_col", Some(str_arg(sort, "column")?.to_string())));
params.push(("sort_desc", Some(bool_arg(sort, "desc").to_string())));
}
params.push(("offset", Some(offset.to_string())));
// One row past the page says whether more rows match.
params.push(("limit", Some((limit + 1).to_string())));
let file = path_enc(key);
let chunk = ctx
.get(&query_path(
ctx.ws(&format!("job_helpers/{endpoint}/{file}")),
&params,
))
.await?;
let mut columns = array(chunk.get("columns")).to_vec();
let mut column_types = array(chunk.get("column_types")).to_vec();
let mut rows = array(chunk.get("rows")).to_vec();
let more_rows = rows.len() as u64 > limit;
rows.truncate(limit as usize);
if let Some(wanted) = args
.get("columns")
.and_then(Value::as_array)
.filter(|c| !c.is_empty())
{
project(&mut columns, &mut column_types, &mut rows, wanted)?;
}
let mut out = s3_object(&key.into(), storage);
if bool_arg(args, "count") {
let count = ctx
.get(&query_path(
ctx.ws(&format!("job_helpers/load_table_count/{file}")),
&selection,
))
.await?;
out.insert("matching_rows".into(), count["count"].clone());
}
let shown = fit_table(&mut out, &columns, &column_types, &rows, offset, more_rows);
if rows.is_empty() {
add_note(
&mut out,
if offset > 0 {
format!("No matching rows past offset {offset}.")
} else {
"No rows match.".to_string()
},
);
}
if shown < rows.len() || more_rows {
out.insert("more".into(), json!({ "offset": offset + shown as u64 }));
}
Ok(pretty(&Value::Object(out)))
}
/// What selects the rows, sent alike to the rows and to their count.
fn selection_params(
args: &Value,
storage: Option<&str>,
) -> Result<Vec<(&'static str, Option<String>)>, String> {
let filters = match args.get("filters") {
None | Some(Value::Null) => None,
Some(Value::Object(f)) if f.is_empty() => None,
Some(f @ Value::Object(_)) => Some(f.to_string()),
Some(_) => return Err("`filters` must be an object from column name to value.".into()),
};
Ok(vec![
(
"search_term",
opt_str_arg(args, "search")
.filter(|s| !s.is_empty())
.map(str::to_string),
),
("filters", filters),
(
"csv_separator",
opt_str_arg(args, "csv_separator").map(str::to_string),
),
(
"csv_has_header",
args.get("csv_has_header")
.and_then(Value::as_bool)
.map(|b| b.to_string()),
),
("storage", storage.map(str::to_string)),
])
}
fn query_path(path: String, params: &[(&str, Option<String>)]) -> String {
let params: Vec<(&str, Option<&str>)> =
params.iter().map(|(k, v)| (*k, v.as_deref())).collect();
with_query(path, &params)
}
/// Keep the requested columns, in the order asked.
fn project(
columns: &mut Vec<Value>,
column_types: &mut Vec<Value>,
rows: &mut [Value],
wanted: &[Value],
) -> Result<(), String> {
let mut indices = vec![];
for name in wanted {
let Some(i) = columns.iter().position(|c| c == name) else {
let known: Vec<&str> = columns.iter().take(50).filter_map(Value::as_str).collect();
let rest = columns.len().saturating_sub(known.len());
return Err(format!(
"Unknown column {name}. The columns are: {}{}.",
known.join(", "),
if rest > 0 {
format!(", and {rest} more")
} else {
String::new()
}
));
};
indices.push(i);
}
*column_types = indices
.iter()
.map(|&i| column_types.get(i).cloned().unwrap_or(Value::Null))
.collect();
*columns = indices.iter().map(|&i| columns[i].clone()).collect();
let names: Vec<&str> = columns.iter().filter_map(Value::as_str).collect();
for row in rows.iter_mut() {
if let Value::Object(cells) = row {
let kept: Map<String, Value> = names
.iter()
.filter_map(|&c| cells.get(c).map(|v| (c.to_string(), v.clone())))
.collect();
*cells = kept;
}
}
Ok(())
}
fn add_note(out: &mut Map<String, Value>, note: impl Into<String>) {
let note = note.into();
let note = match out.get("note").and_then(Value::as_str) {
Some(before) => format!("{before} {note}"),
None => note,
};
out.insert("note".into(), note.into());
}
fn is_image_key(key: &str) -> bool {
key.rsplit_once('.')
.is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_lowercase().as_str()))
@@ -341,15 +522,18 @@ fn fit_text(out: &mut Map<String, Value>, content: &str, file_cut: bool, csv_cut
}
}
/// The schema and rows of a Parquet preview that fit the result. The schema takes at most
/// half the room, long strings are cut at any depth, and a first row too wide on its own
/// keeps its leading columns.
fn fit_parquet(
/// The schema and rows of a table that fit the result; how many rows were kept. The schema
/// takes at most half the room, long strings are cut at any depth, and a first row too wide
/// on its own keeps its leading columns. `first_row` is the offset of `returned`, and
/// `more_rows` whether rows past it were left unread.
fn fit_table(
out: &mut Map<String, Value>,
columns: &[Value],
column_types: &[Value],
returned: &[Value],
) {
first_row: u64,
more_rows: bool,
) -> usize {
let schema_room = room(out) / 2;
let mut used = 0;
let mut listed = 0;
@@ -378,7 +562,7 @@ fn fit_parquet(
columns.len()
));
}
fit_rows(out, returned, columns.len(), notes);
fit_rows(out, returned, columns.len(), notes, first_row, more_rows)
}
fn fit_rows(
@@ -386,7 +570,9 @@ fn fit_rows(
returned: &[Value],
column_count: usize,
mut notes: Vec<String>,
) {
first_row: u64,
more_rows: bool,
) -> usize {
let mut room = room(out);
let mut cut_cells = false;
let mut rows = vec![];
@@ -418,10 +604,13 @@ fn fit_rows(
}
break;
}
if rows.len() < returned.len() || returned.len() == PARQUET_PREVIEW_ROWS {
notes.push(match rows.len() {
1 => "The first row only.".to_string(),
n => format!("The first {n} rows only."),
let shown = rows.len();
if shown < returned.len() || more_rows {
notes.push(match (first_row, shown) {
(0, 1) => "The first row only.".to_string(),
(0, n) => format!("The first {n} rows only."),
(o, 1) => format!("Row {} only.", o + 1),
(o, n) => format!("Rows {}-{} only.", o + 1, o + n as u64),
});
}
if cut_cells {
@@ -438,6 +627,7 @@ fn fit_rows(
if !notes.is_empty() {
out.insert("note".into(), notes.join(" ").into());
}
shown
}
/// Cut every string in `value` to `MAX_CELL_CHARS`; whether one was.
@@ -549,15 +739,20 @@ mod tests {
let names: Vec<Value> = wide.keys().map(|k| json!(k)).collect();
let types = vec![json!("Utf8"); 100];
let mut out = file();
fit_parquet(
let kept = fit_table(
&mut out,
&names,
&types,
&[Value::Object(wide.clone()), Value::Object(wide)],
100,
false,
);
let shown = fits(out);
assert_eq!(kept, 1);
assert_eq!(shown["rows"].as_array().unwrap().len(), 1);
assert!(shown["note"].as_str().unwrap().contains("of 100 columns."));
let note = shown["note"].as_str().unwrap();
assert!(note.starts_with("Row 101 only."), "{note}");
assert!(note.contains("of 100 columns."), "{note}");
// The endpoint's schema arrays name every column, however many there are.
let names: Vec<Value> = (0..2000).map(|i| json!(format!("{i:0>36}"))).collect();
@@ -567,7 +762,7 @@ mod tests {
.map(|n| (n.as_str().unwrap().to_string(), json!("v")))
.collect();
let mut out = file();
fit_parquet(&mut out, &names, &types, &[Value::Object(row)]);
fit_table(&mut out, &names, &types, &[Value::Object(row)], 0, false);
let shown = fits(out);
assert!(shown["note"]
.as_str()
@@ -576,7 +771,14 @@ mod tests {
let nested = json!({ "id": 1, "tags": ["y".repeat(1_000_000)] });
let mut out = file();
fit_parquet(&mut out, &[json!("id"), json!("tags")], &[], &[nested]);
fit_table(
&mut out,
&[json!("id"), json!("tags")],
&[],
&[nested],
0,
false,
);
let shown = fits(out);
assert_eq!(
shown["rows"][0]["tags"][0].as_str().unwrap().len(),
@@ -584,6 +786,34 @@ mod tests {
);
}
/// The endpoints return every column, so `columns` is applied to what they return.
#[test]
fn table_columns_are_projected_in_the_order_asked() {
let mut columns = vec![json!("id"), json!("name"), json!("amount")];
let mut types = vec![json!("Int64"), json!("Utf8"), json!("Float64")];
let mut rows = vec![
json!({ "id": 1, "name": "a", "amount": 2.5 }),
json!({ "id": 2 }),
];
project(
&mut columns,
&mut types,
&mut rows,
&[json!("amount"), json!("id")],
)
.unwrap();
assert_eq!(columns, vec![json!("amount"), json!("id")]);
assert_eq!(types, vec![json!("Float64"), json!("Int64")]);
assert_eq!(
rows,
vec![json!({ "amount": 2.5, "id": 1 }), json!({ "id": 2 })]
);
let err = project(&mut columns, &mut types, &mut rows, &[json!("nope")]).unwrap_err();
assert_eq!(err, "Unknown column \"nope\". The columns are: amount, id.");
assert_eq!(table_endpoint("a/b.NDJSON"), Some("load_csv_preview"));
assert_eq!(table_endpoint("a/b.json"), None);
}
#[test]
fn image_type_comes_from_the_bytes() {
assert_eq!(sniff_image(b"\xff\xd8\xff\xe0rest"), Some("image/jpeg"));
@@ -51,6 +51,55 @@ const readS3FileSchema = z.object({
"Also open the file in the side panel next to the chat. Only when the user asks to open or display the file itself: reading it to answer a question about it does not. Only Windmill's own chat has that panel; elsewhere the result's `link` opens the file."
)
})
const queryS3TableSchema = z.object({
s3: s3KeyArg,
storage: storageArg,
columns: z
.array(z.string())
.optional()
.describe('Columns to return, in this order. Omit for every column.'),
search: z
.string()
.optional()
.describe('Keep the rows where any column contains this text, ignoring case.'),
filters: z
.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
.optional()
.describe(
'Keep the rows that match every filter, by column name. A number column takes a number or a comparison such as `">=10"` or `"!=0"`; a boolean column takes true or false; a text column takes a substring, matched ignoring case, or `"=value"` for an exact match.'
),
sort: z
.object({ column: z.string(), desc: z.boolean().optional() })
.optional()
.describe('Sort the matching rows by one column, ascending unless `desc` is true.'),
offset: z
.number()
.int()
.min(0)
.optional()
.describe(
'Matching rows to skip: pass `more.offset` from the previous call for the next page.'
),
limit: z
.number()
.int()
.min(1)
.max(500)
.optional()
.describe('Max number of rows to return. Defaults to 50.'),
count: z
.boolean()
.optional()
.describe('Also return `matching_rows`, the number of rows that match.'),
csv_separator: z
.string()
.optional()
.describe('Column separator of a CSV or TSV file. Detected when omitted.'),
csv_has_header: z
.boolean()
.optional()
.describe('Whether the first line of a CSV or TSV file names the columns. Defaults to true.')
})
const deleteS3FileSchema = z.object({ s3: s3KeyArg, storage: storageArg })
const moveS3FileSchema = z.object({
s3: s3KeyArg,
@@ -68,6 +117,11 @@ const readS3FileToolDef = createToolDef(
'read_s3_file',
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, the first rows of a Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only."
)
const queryS3TableToolDef = createToolDef(
queryS3TableSchema,
'query_s3_table',
"Rows of a table file in the workspace's object storage: CSV, TSV, Parquet, or newline-delimited JSON (.jsonl, .ndjson). The server filters, searches, sorts and pages, so filter here rather than reading rows to find a value. Returns the columns and their types, the rows as objects, and `more` with the offset of the next page when more rows match."
)
const deleteS3FileToolDef = createToolDef(
deleteS3FileSchema,
'delete_s3_file',
@@ -141,6 +195,30 @@ export function getStorageTools(): SessionTool<{}>[] {
return JSON.stringify(result, null, 2)
}
},
{
requires: NONE,
def: queryS3TableToolDef,
planModeSafe: true,
lookup: true,
showDetails: true,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const parsed = queryS3TableSchema.parse(args)
const storage = parsed.storage === '_default_' ? undefined : parsed.storage || undefined
const name = `${parsed.s3}${storageLabel(storage)}`
toolCallbacks.setToolStatus(toolId, { content: `Querying ${name}...` })
const { text } = await runOnServer('query_s3_table', workspace, args)
const result = JSON.parse(text)
const rows = `${result.rows.length} row(s)`
const total = result.matching_rows != null ? ` of ${result.matching_rows}` : ''
const selected = parsed.search || Object.keys(parsed.filters ?? {}).length > 0
toolCallbacks.setToolStatus(toolId, {
content: `Queried ${name}: ${rows}${total}${selected ? ' matching' : ''}`,
result,
s3File: { s3: parsed.s3, ...(storage ? { storage } : {}) }
})
return text
}
},
{
requires: NONE,
def: deleteS3FileToolDef,