Repository navigation
Conversation
…from prompts The PBIP dashboard needs a Power BI license and fixed pages, so there is no quick way to ask an ad hoc question of agent_events and see it as a chart. dashboards/power_bi/copilot/ is a static page that turns a prompt such as "p95 LLM latency by model for the last 7 days" into a dashboard page: KPI cards with period-over-period change, cross-filtering charts, a written summary, and the BigQuery SQL for each visual. Prompts are matched to the same page themes as the PBIP report (activity, tokens, tool usage, latency, errors) with keyword rules in the browser. Nothing is sent to a server, and the page never connects to BigQuery: it starts from a synthetic sample, and Import data loads rows exported from agent_events as JSON, JSON Lines, or CSV. Labels and imported values are HTML-escaped, filter values are written as escaped SQL string literals, the table ID uses the PBIP identifier rules, and CSV export follows RFC 4180. tests/test_power_bi_copilot.py checks license headers, vendor names, local- only assets, and element IDs. When Node.js is available it runs tests/power_bi_copilot_smoke.js, which drives app.js through prompts, SQL generation, import, and a CSV round trip against a DOM stub. The PBIP project, its generator, and its locks are unchanged.
- Donut: fold groups past the top five into an "Other" slice that can't be cross-filtered, compute shares over the full series, and show shares and the centre total only for additive metrics. - Line chart: cap percentage axes at 100 and clamp plotted values. - Copy SQL: use the Clipboard API only in secure contexts and fall back to selecting the SQL. - Schema view: list all 17 agent_events columns, including event_id. - README: skip content_parts in the export query.
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
caohy1988
left a comment
There was a problem hiding this comment.
Thanks for putting this together. A browser-only preview is a handy way to try page layouts without a Power BI install.
One thing I'd like fixed before this goes in: CSV export writes imported strings as they are, apart from RFC 4180 quoting (csvCell in dashboards/power_bi/copilot/app.js, used by the export handler around line 1947). Fields like the agent name and especially error_message often carry text that came from tools or other people's agents writing to the same table, so a cell that starts with =, +, -, @, a tab or a CR turns into a live formula when someone opens the file in Excel or Sheets. Quoting doesn't prevent that. Prefixing those cells with a ' (after any leading whitespace) before quoting, plus a smoke-test case with a formula-leading value, would close it. The current smoke test only checks comma and quote escaping, so it passes either way.
A few other things worth a look, roughly in order of importance:
- Token totals: the importer and the generated SQL only read
total_token_count, but the SDK's logger writesusage_metadata.total_tokensand the reporting views also fall back tocontent.usage.total, so real SDK data can show zero tokens. - The README's
bq query --format=jsonoutput has UTC timestamps with no offset.Date.parsetreats those as local time, so in a US time zone a late-evening event moves to the next day. - P95 uses
floor(p * n / 100)as the index, which picks the next value at exact rank boundaries (nineteen 1 ms calls and one 1,000 ms call give a P95 of 1,000 ms).ceil(p * n / 100) - 1matches the nearest-rank definition the README describes. - Export CSV uses
filterRows()without the explorer search, so the file can include rows the user had filtered out. - The copied SQL doesn't always match the page it came from (KPI window and comparison, top-N members on charts, the donut tail), which makes "copy SQL" misleading.
- One malformed row rejects the whole import, while the README says bad rows are skipped and counted.
tests/test_power_bi_copilot.pyisn't pyink-formatted, so the Format check will probably fail.
- CSV export: prefix text cells that start with = + - @, a tab, or a CR with an apostrophe so spreadsheets don't run them as formulas; the importer strips the prefix again. Export now writes the rows the table view shows, including the search box. - Import: read zone-less timestamps such as `bq --format=json` output as UTC, read token totals from usage_metadata.total_tokens and content.usage as well as total_token_count, and skip and count a malformed row instead of rejecting the whole import. - P95: use the nearest-rank index ceil(p * n / 100) - 1. - SQL: anchor the window on the newest day with data, return the previous window for the KPI deltas, ignore a visual's own cross-filter, and return the same top members as each chart, folding the donut tail into "Other". - Tests: smoke cases for the formula guard, UTC timestamps, token fallbacks, export with search, a malformed JSON Lines row, the P95 boundary, and the donut SQL; wrap a long line for pyink.
Page and visual ids came from Date.now() alone, so two created in the same millisecond collided and the older page reopened. That also made the smoke test fail about half the time. Add a counter to the id, and apply pyink's import spacing to the test module.
|
@beriwalp, on the two questions in the description:
On GitHub Pages: as you say, nothing here publishes it. The Pages workflow only copies |
caohy1988
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. The formula guard on CSV export, exporting what the table view shows, UTC handling, nearest-rank P95 and the unique page ids all look right, and the smoke test no longer flakes.
Two things I'd like fixed before this goes in:
- The formula guard isn't reversible.
csvCellonly prefixes values that matchFORMULA_LEAD, so a literal'@billingis exported unchanged and ends up byte-identical to the guarded export of@billing. On import,unguardthen strips the apostrophe from both, and it does that for any CSV, not just files this page exported. Importing both names as JSON, exporting and re-importing collapses them into one agent, and an ordinary CSV with an error message starting'--flagloses its apostrophe. Also prefixing values that already start with'followed by a formula-like remainder (so one strip restores them), plus smoke cases for'@x/'=x, would fix it. tests/test_power_bi_copilot.pyfails the isort step of the Format check: the latest commit dropped the blank line betweenimport pytestand the first-partyfrom tests.test_power_bi_dashboard import .... Running./autoformat.shrestores it.
Other things worth a look, roughly in order of importance:
- Tool error rate only counts
TOOL_ERROR, but the producer also emitsTOOL_COMPLETEDwith an error status, so a failed call can show a 0% error rate and an empty Recent errors table. The same applies to the generated SQL. - The generated SQL finds
window_endonly among rows from the last2 * daysbeforeCURRENT_TIMESTAMP(), so for a table with no recent data the anchor is NULL and every query returns nothing while the page shows data. The README describes both anchoring behaviors (around lines 20-25 and 92-94). - Table visuals always render slowest calls or recent errors and ignore their metric and dimension (display and SQL), and once a page is switched to "table" it can't be switched back.
- Copied visual SQL still doesn't match what the chart shows: date visuals rendered as bar or donut get the full per-day query with no limit or "Other" folding, groups with null measures are kept, and the slowest-calls query includes calls with no latency.
- Prompt parsing looks for the metric and dimension independently across the whole prompt, so "add tool calls by agent" groups by tool and "add events by user" counts distinct users. "Make a new page with a bar chart of ..." converts the current page's charts instead of adding a page, and "+ Prompt a new page" keeps "Modify current" selected.
- Missing trace IDs fall back to the invocation ID, and missing token fields count as zero, so the page reports traces and 0 tokens / 0% cache hit where the SQL returns 0 traces and NULLs.
- Smaller: Copy SQL still copies the previous table's query after the table ID becomes invalid; duplicating a page keeps its visual ids (and Focus repeats the line-chart gradient id); line charts over categorical dimensions cut the first five characters off every label; a damaged first JSON Lines record sends the whole paste through the CSV parser; the schema view lists
event_idas a standard column andcontent_partsas JSON rather than a repeated record; and the smoke test's stub never binds chart handlers, so removing cross-filtering or chart escaping still passes.
caohy1988
left a comment
There was a problem hiding this comment.
I took another look after the merge from main. The merge itself is clean and the Power BI copilot files are unchanged, so the two problems from my last review are still there:
- The CSV formula guard isn't reversible.
csvCell(dashboards/power_bi/copilot/app.js~L643) only prefixes values that look like formulas, so a literal'@billingexports byte-identical to the guarded@billing, and both come back as one agent on re-import.unguard(~L1847) also strips a leading apostrophe from every imported CSV, not only files this page exported, so an ordinary CSV with an error message like'--flagshows--flag. Prefixing values that already start with an apostrophe followed by a formula-like character ('@x→''@x) keeps a single strip on import correct; round-trip smoke cases for'@x,'=xand'--flagwould lock it in. - The format check fails on the new test file.
tests/test_power_bi_copilot.pyneeds a blank line betweenimport pytestand thefrom tests.test_power_bi_dashboard import ...line.isort --check-onlyexits 1 on it, so the Format job will fail. Running./autoformat.shfixes it.
The other points from before (tool calls logged as TOOL_COMPLETED with status=ERROR showing a 0% error rate, and the copied SQL returning nothing for a table whose newest data is older than twice the window) still apply too and are worth fixing in this PR if you can.
Required: - CSV formula guard is reversible: values that already start with an apostrophe followed by a formula-like remainder get one more, so one strip on import restores them. Import strips it only from files with this page's export header; other CSVs keep their text. - Restore the isort blank line before the first-party test import. Also: - Count TOOL_COMPLETED with status ERROR as a tool error (KPIs, Recent errors, and SQL). - SQL falls back to the whole table for the window anchor when recent partitions are empty; README describes the anchoring consistently. - Table visuals: a switched chart keeps its metric and dimension as a table and can switch back; only the row lists stay tables. - Copied SQL matches the charts: newest days for per-day bars and donuts, groups with no value dropped, and slowest calls need a latency. - Prompts read the metric before "by" and the dimension after it; "new page" asks create a page; "+ Prompt a new page" leaves modify mode. - Missing trace IDs and token fields stay missing instead of falling back to the invocation ID or zero. - Invalid table ID clears the SQL and disables Copy; duplicated pages and repeated charts get unique visual and gradient ids; line labels are only trimmed for dates; JSON Lines detection survives a damaged first line; timestamps accept microsecond and exponent epochs and +HH / spaced offsets; schema view marks event_id and content_parts accurately. - Smoke test: the DOM stub now finds elements in rendered HTML so chart handlers bind, with cases for escaping, cross-filtering, and each fix.
caohy1988
left a comment
There was a problem hiding this comment.
Re-reviewed at 5e38584. Thanks for the round-3 fixes. The TOOL_COMPLETED error-status count and the isort issue in the new test are fixed, and the old-data fallback now finds the right anchor for a table last written in 2020. The page's own CSV export round-trips '@x, '=x and '--flag correctly. tests/test_power_bi_copilot.py (17 passed) and the node smoke test pass at this head.
Two metric bugs need fixing before this goes in:
Failed LLM responses are left out of the error rate. dashboards/power_bi/copilot/app.js:529-536 counts every LLM_RESPONSE as a call but only increments the failure count for LLM_ERROR, and the generated SQL does the same (around line 259). The logger emits LLM_RESPONSE with status="ERROR", and the page's own isErrorRow (line 500) already puts those in Recent errors, so one errored response on the Errors page shows 0.0% next to an error in the list. Using one failed-LLM predicate in both the card and METRICS.error_rate.sql fixes it. A smoke case for an error-status LLM_RESPONSE would catch it next time.
Missing cache telemetry shows as a measured 0% hit rate. app.js:577 turns a null cached-token sum into zero whenever prompt tokens exist, which is the producer's normal output when caching isn't reported. The copied SQL returns NULL for the same data, so the page and the query disagree. It should show unknown unless at least one cached-token value is present, and keep an explicit zero as a real 0%.
Smaller things worth a look while you're in there:
- An export with multiline diagnostics can't be re-imported:
app.js:1999guesses JSON Lines from any physical line starting with{before checking for a CSV header. - The copied SQL compares raw status (
status = 'ERROR'vs seed values likeerror) while the page uppercases on import, and an emptyattributes.modelhides a validmodel_version(app.js:1031). - A CSV from another source with the same 21 columns still loses a literal leading apostrophe (
app.js:2015), and the fallback predicate skips pre-1970 timestamps (app.js:1018).
- Error rate counts an LLM_RESPONSE logged with an ERROR status as a
failure, on the page and in SQL, using one failed-call predicate that
matches isErrorRow().
- Cache hit rate is unknown unless some row reports cached tokens; an
explicit zero is still a real 0%, matching SAFE_DIVIDE in SQL.
- A CSV header line wins over stray "{" lines, so exports with multiline
diagnostics re-import.
- SQL upper-cases status once in the temp table, and an empty
attributes.model falls back to model_version.
- Export adds a copilot_formula_guard column; import removes the formula
guard only when it's present, so a same-column CSV from elsewhere keeps
a literal leading apostrophe.
- The fallback window anchor covers timestamps before 1970.
- Smoke cases for each, and README updates.
caohy1988
left a comment
There was a problem hiding this comment.
Thanks for the turnaround on the last review. Both of those issues look fixed at this head: an errored LLM_RESPONSE now raises the error rate (one failed and one successful response shows 50%), and missing cache telemetry shows as -- rather than a measured 0% (an explicit zero still shows 0%). The multiline CSV re-import, raw-status comparison, empty model falling through to model_version, the foreign 21-column apostrophe case, and the pre-1970 fallback are fixed too. The new tests fail on the previous page script and pass here.
Approving. I hit a few things while probing that I'd like to see in a follow-up (the issue is linked below). The important ones:
- The built-in "by agent" prompt can drop other agents.
app.js:766searches the whole prompt for every imported agent name, and the starter at line 1851 contains "by agent". If an agent is literally namedagent, that word also sets the global agent slicer, so the chart, KPI, CSV and copied SQL cover only that agent. - "Failed calls only" can remove every failed call. The prompt compiles to a status equality (
app.js:782), but failedLLM_ERROR/TOOL_ERRORrows can have a null status. The global filter then drops them before Recent errors sees them. After that prompt, a dataset of two explicit error events plus one success showed--and an empty Recent errors query; the two failed calls should have stayed at 100%. - Cache hits in
content.usage.cached_tokensare ignored. The page and the SQL projection (app.js:2000,:1065) don't read that field, even though the README documentscontent.usageand the SDK emits it. A row with 80 cached tokens showed--for cache hits; mixed with an explicit zero it became 0% instead of 40%. - Copied SQL fails when the events table omits a payload column. The temp table always selects
attributes,contentandlatency_ms(app.js:1051). The SDK can physically omit any of them, so even a Sessions page fails before the first KPI. The README export also usesEXCEPToncontent_parts, which requires that column to exist. - The README metrics table still describes the old error-rate rule (only
LLM_ERRORandTOOL_ERROR), while the code and the paragraph later in the README also count responses and completions with anERRORstatus. - Generated SQL day boundaries use the project's default time zone (
DATE(timestamp)andTIMESTAMP(...)with no zone atapp.js:1030-1079), while the page buckets by UTC. In a project whose default isn't UTC, the copied SQL and the page disagree on the same rows. - A line chart over a non-date dimension has no cap, so "switch to line" on "Top users by sessions" plots every member (and its SQL has no
LIMIT). Bars already cap at a top N. - The CSV formula guard only looks at the start of a cell. A value like
x;=1+1;yis exported unchanged, and a spreadsheet that splits on;can treat=1+1as a formula.
Smaller ones: missing status is OK on the page and NULL in SQL; an empty tool doesn't fall through to tool_name the way model now does; timestamp import drops microseconds and can reverse Recent errors; tied chart members can differ between the page and SQL; a 0% donut and its query disagree on membership; clicking a categorical line point (or a per-day bar that still says "Click to cross-filter") doesn't filter; the committed SQL regression test can still pass if only the error-rate numerator is broken, because it searches the whole script; and the documented 30-day import with a 5,000-row cap can turn a flat session count into a huge delta.
The Power BI tests and the node smoke test pass at this head, as do isort and pyink on the new Python test file.
Follow-ups: #611
caohy1988
left a comment
There was a problem hiding this comment.
This is a re-review after main was merged into the branch. The seven preview files are unchanged from the last approved head, the merge itself is a clean three-way merge with no overlapping paths, and the behavior approved last time still holds: an errored LLM response raises the error rate, and missing cache telemetry shows as -- rather than a measured 0%.
Approving. Everything in #611 is still open — nothing there was fixed or made worse, and the merge did not introduce a new regression. I left one small extra note on that issue about a test-coverage gap (the static “loads nothing from the network” check misses scheme-relative URLs and stylesheet imports). The page itself is still clean on that front.
The 17 Copilot tests and the rest of the Power BI suite pass at this head, including the smoke test. Reverts of the two previously approved fixes still fail that smoke test, as they should. Importing the 92 events from the merged demo produced 8 sessions and a 30.8% error rate, which matches an independent count.
Why
The PBIP dashboard needs a Power BI license and has fixed pages, so there's no quick way to ask an ad hoc question of
agent_eventsand see the answer as a chart. This PR adds a preview of a prompt-driven authoring flow, to get feedback on whether it's worth taking further.What
dashboards/power_bi/copilot/is a static page (HTML, CSS, JS, no dependencies). A prompt such as "p95 LLM latency by model for the last 7 days" or "which tools fail most" builds a dashboard page with:Prompts are matched to the same themes as the PBIP report pages (activity, tokens, tool usage, latency, errors) using keyword rules in the browser. Anything else gets a page built from the metric and dimension the prompt names.
Scope and limits
agent_eventsrows exported as JSON, JSON Lines, or CSV (for examplebq query --format=json).APPROX_QUANTILES, so values can differ slightly.dashboards/power_bi/README.md.Safety
Testing
tests/test_power_bi_copilot.py(matched by the existingtests/test_power_bi_*.pyCI glob): license headers, vendor-name check, local-only assets, every element ID the script reads exists inindex.html, whitespace hygiene.tests/power_bi_copilot_smoke.js, which bootsapp.jsagainst a DOM stub and checks:jsonschemalocally, so the existing Power BI suite will first run in CI. The new folder holds no JSON or TMDL, and the generator and validator only walk the PBIP item folders.Feedback wanted
dashboards/power_bi/copilot/the right home, or should this be a sibling ofpower_bi/?A follow-up commit addresses early review feedback: a donut "Other" slice with shares over the full series, percentage axes capped at 100, a Copy SQL fallback outside secure contexts,
event_idin the schema view (17 columns), andEXCEPT(content_parts)in the README export query.@caohy1988, could you take a look?