| 412 | } |
| 413 | |
| 414 | export async function getTracesAndRelabelsForUser( |
| 415 | userId?: string, |
| 416 | limit: number = 50, |
| 417 | cursor: string | undefined = undefined, |
| 418 | dataset: string = DATASET, |
| 419 | joinType: 'INNER' | 'LEFT' = 'LEFT', |
| 420 | ) { |
| 421 | // Get recent traces for the user and any associated relabels |
| 422 | const query = ` |
| 423 | WITH traces AS ( |
| 424 | SELECT |
| 425 | id, |
| 426 | agent_step_id, |
| 427 | user_id, |
| 428 | created_at, |
| 429 | type, |
| 430 | payload |
| 431 | FROM \`${dataset}.${TRACES_TABLE}\` |
| 432 | WHERE type = 'get-relevant-files' |
| 433 | ${userId ? `AND user_id = '${userId}'` : ''} |
| 434 | ${cursor ? `AND created_at < '${cursor}'` : ''} |
| 435 | ORDER BY created_at DESC |
| 436 | LIMIT ${limit} |
| 437 | ) |
| 438 | SELECT |
| 439 | t.id, |
| 440 | ANY_VALUE(t.agent_step_id) as agent_step_id, |
| 441 | ANY_VALUE(t.user_id) as user_id, |
| 442 | ANY_VALUE(t.created_at) as created_at, |
| 443 | ANY_VALUE(t.type) as type, |
| 444 | ANY_VALUE(t.payload) as payload, |
| 445 | ARRAY_AGG(r IGNORE NULLS) as relabels |
| 446 | FROM traces t |
| 447 | ${joinType === 'INNER' ? 'INNER JOIN' : 'LEFT JOIN'} \`${dataset}.${RELABELS_TABLE}\` r |
| 448 | ON t.agent_step_id = r.agent_step_id |
| 449 | AND t.user_id = r.user_id |
| 450 | AND JSON_EXTRACT_SCALAR(t.payload, '$.user_input_id') = JSON_EXTRACT_SCALAR(r.payload, '$.user_input_id') |
| 451 | GROUP BY t.id |
| 452 | ORDER BY ANY_VALUE(t.created_at) DESC |
| 453 | ` |
| 454 | |
| 455 | const [rows] = await getClient().query(query) |
| 456 | |
| 457 | // Process and parse the results |
| 458 | return rows.map((row) => { |
| 459 | // Create trace object from individual fields |
| 460 | const trace = { |
| 461 | id: row.id, |
| 462 | agent_step_id: row.agent_step_id, |
| 463 | user_id: row.user_id, |
| 464 | created_at: row.created_at, |
| 465 | type: row.type, |
| 466 | payload: |
| 467 | typeof row.payload === 'string' ? JSON.parse(row.payload) : row.payload, |
| 468 | } as GetRelevantFilesTrace |
| 469 | |
| 470 | // Parse relabel payloads (if any exist) |
| 471 | const relabels = |