Commit Graph
11 Commits
Author SHA1 Message Date
Davide Silvestri 0bb39e36c6 [1/4] feat: AI assistant eval platform on self-hosted Phoenix (#5958)
* feat: add Phoenix LLM tracing service to the dev stack (ai profile)

* chore(deps): add openinference pydantic-ai instrumentation (dev)

* feat: export assistant traces to Phoenix when BASEROW_ASSISTANT_PHOENIX_URL is set

* fix: harden Phoenix tracing setup after review

* feat: Phoenix postgres storage, ai-evals profile and auth support

* docs: ADR 007 and assistant tracing/evals guides

* feat: assistant eval platform core (types, registries, scenarios)

* feat: eval harness with shared assistant factory

* feat: phoenix dataset sync for assistant evals

* feat: assistant eval experiments via phoenix client + CLI

* feat: migrate core, database and docs evals to the platform

Ports the 42 kuma-core/kuma-database/kuma-docs pytest evals into
declarative EvalCase/EvalScenario registrations, plus structure-level
tests asserting dataset counts, ids, and scenario wiring.

* feat: migrate builder and automation evals to the platform

Ports the 12 builder + 2 proactive + 2 user-source cases into
evals/datasets/builder.py (kuma-builder, 16 cases) and the 7 automation
cases into evals/datasets/automation.py (kuma-automation), following the
Task 5 pattern established in core.py/database.py. Extends
eval_platform/test_datasets.py with counts, id lists, a mode-per-case
assertion, and pre_state snapshot checks for the two cases that need one.

* fix: link traces and final counts for single-case eval runs

* fix: root spans for single-case eval runs use the assistant tracer provider

* feat: assistant eval runner service with run page

Adds the assistant_eval_runner management command (migrate -> instrumentation
-> dataset sync -> single worker thread -> wsgiref server) and its
runner.py module: a stdlib WSGI app serving a plain server-rendered page
(GET /, POST /run, GET /healthz) backed by a bounded in-memory run history
and one background worker draining a queue.Queue via run.run_experiment_for.

Wires the assistant-eval-runner compose service (ai-evals profile, own
baserow_evals DB), renames phoenix-db-init to ai-evals-db-init and extends
it to also create baserow_evals, and adds BASEROW_EVAL_RUNNER_PORT to both
env example files and the dev docs.

* fix: eval runner integration fixes

assistant-eval-runner needs its own SECRET_KEY/DATABASE_*/REDIS_* env vars:
dev-overlay compose services don't inherit docker-compose.yml's
x-backend-variables anchor (that's file-scoped YAML), so the container was
starting without a Django SECRET_KEY and without a Redis password, crashing
on auth. Also links to finished experiments pointed at the container-internal
BASEROW_ASSISTANT_PHOENIX_URL (http://phoenix:6006), unreachable from the
developer's browser.

Adds BASEROW_ASSISTANT_PHOENIX_PUBLIC_URL (defaulting to
http://localhost:${BASEROW_PHOENIX_PORT:-6060}) and has runner.py build the
Phoenix link from it, deep-linking straight to the finished run's experiment
compare view when its dataset_id/experiment_id are known, falling back to
the datasets list otherwise.

* refactor: retire the pytest eval harness

All 65 eval cases now live in baserow_enterprise.assistant.evals.datasets;
delete the legacy pytest-based suite and its `eval` markers.

* docs: rewrite assistant evals guide for the Phoenix platform

* feat: docs judge, prompt sync, git stamping and UI-contributed eval examples

- answer_quality LLM-as-judge evaluator for kuma-docs (BASEROW_EVAL_JUDGE_MODEL)
- Kuma prompts versioned into Phoenix on sync; experiments stamped with
  prompt hashes, git branch/commit and judge model
- sync preserves UI-added dataset examples with prompt-match adoption;
  eval-export emits paste-ready docs.py snippets
- final-review fixes: skip-safe scoring, runner CSRF/bind hardening,
  doc corrections

* feat: eval runner UI round — tabs, fan-out, reference answers, 64-case docs dataset

- Runner page: dataset tabs with selection badges, per-dataset and global
  all/none, cross-dataset fan-out (one experiment per dataset), 5s
  auto-refresh of runs, persistent run history across restarts, per-dataset
  Phoenix links, in-page Help tab rendering the repo docs via /docs.json.
- Reference answers for kuma-docs: EvalCase.reference_answer, judge grades
  against it, sync preserves UI-curated ones, eval-export round-trips them.
- kuma-docs grown to 64 cases: reference answers for all, PostHog-mined
  frequent questions, and cannot-do guardrail cases.
- Gemini (google:gemini-3.6-flash) in the eval model list.

* feat: runnable UI examples, prompt overrides, eval baseline and results view

- UI-added Phoenix examples now execute: docs questions get the standard
  docs checks + judge; tool cases declare scenario/expected_tools/
  answer_contains in metadata (empty-workspace default scenario). They are
  tickable per dataset on the runner page and run in whole-dataset
  experiments too.
- Prompt overrides: run any experiment with a prompt's latest Phoenix
  version instead of the code constant (runner checkbox panel with soft
  per-tab ordering, or --override-prompt). Agent singletons keep their
  dynamic instructions; effective hashes + override list stamped on the
  experiment.
- Committed baseline snapshot (evals/baseline.json, 111 cases) with
  just b eval-baseline capture/import; the runner imports it on startup so
  every Phoenix instance gets a baseline experiment per dataset,
  idempotent by content hash and run count.
- Results tab: all datasets in one view for a named experiment, with
  baseline deltas and a case-weighted overall row, via Phoenix experiment
  annotation summaries.
- New evaluation guide (docs/testing/ai-assistant-eval-analysis.md) served
  in the Help tab; layout uses horizontal space better (single tab row,
  fluid case columns).

* feat: time and cost in eval results, frozen into the baseline snapshot

- Results tab gains time (sum of run latencies) and cost/token columns per
  dataset and summed overall, with lower-is-better baseline deltas.
- eval-baseline capture freezes each dataset's time/cost/token totals into
  baseline.json; import stamps them as metadata so imported baselines
  (which carry no traces to price) still show time and cost.
- Importing a new baseline supersedes the previously imported one instead
  of accumulating duplicates.
- Changelog entry for the eval platform.

* fix: OpenInference attributes on subset-run task root spans

Bare wrapper spans rendered as kind 'unknown' with Unset status and empty
input/output in Phoenix. The Task root span now carries the CHAIN kind, the
case prompt as input, the run result as JSON output, and an explicit OK
status.

* polish; minor fixes

* fix: address eval platform review feedback

Apply production model settings and retries, isolate automation checks, and fix runner configuration, links, and result status.

Defer GPT-5.6 compatibility and baseline comparisons to #6034.

* fix: preserve model profiles in rebased eval harness

Use an explicit model profile for evals and share concrete models with tools. Manage model clients through the existing lifecycle helper and preserve regression coverage from the retired harness.

* fix: harden eval persistence and Phoenix access
2026-09-09 17:06:07 +02:00
Davide Silvestri ab45c2346a feat [4/8]: per-feature AI model settings (#5796)
* feat: per-feature and workspace-level AI model settings

Baserow could only point every AI feature at one instance-wide model. An
administrator can now register provider models, declare which AI features each
model may serve, and pick the default model per feature; a workspace admin can
inherit that choice, override it, or disable the feature locally.

The assistant resolves its model once per logical request and threads that
snapshot through its nested agents and tools, so a single run can no longer
re-read settings repeatedly or pick a model other than the one it validated.
The scoped provider state is memoized for the duration of a request, keeping
workspace serialization from loading it once per workspace.

Also:
- add Google and Groq provider types, and keep these database-only providers
  out of the legacy workspace settings they cannot round-trip through;
- prune orphaned feature selections so an unloaded feature type's RESTRICT FK
  no longer blocks provider and model deletion;
- record whether a configured model answers text and tool-calling probes, and
  invalidate that result when its credentials or identifier change;
- broadcast provider and availability changes over the existing realtime
  channel so open clients update without reloading;
- read the assistant model from the shared configmap, so frontend pods no
  longer miss it on Helm installs.

Manual test instructions live in docs/testing/kuma-model-settings-test-plan.md.

* fix: address AI provider settings review feedback
2026-09-04 10:53:53 +02:00
Davide Silvestri 1fa388b83f chore(deps): upgrade pydantic-ai to V2 (2.28.0) (#5896)
* chore(deps): upgrade pydantic-ai to V2 (2.28.0)

Upgrades pydantic-ai-slim from 1.102.0 to 2.28.0. No user-visible behaviour
change: where V2 moved a default, the V1 behaviour is pinned rather than
silently adopted.

Production changes are five files:

  assistant/assistant.py            async for -> async with ... as events:
                                    (run_stream_events is a context manager)
  assistant/retrying_model.py       public RunContext; state/metadata/
                                    close_stream proxy delegation; Vertex AI
                                    via GoogleCloudProvider
  core/generative_ai/registries.py  output_retries=3 -> retries={"output": 3}
  assistant/model_profiles.py       normalise google-gla/google-vertex prefixes
  assistant/tools/database/agents.py  pin end_strategy="early"

The rest of the diff is test hardening, and it is the point of the change.
The assistant suite mocked pydantic-ai's streaming path instead of running it,
which hid four real breaks — one of them user-facing:

  - Agent(output_retries=3) raises TypeError on V2, breaking the premium
    generate_ai_formula endpoint. Invisible because the test patches prompt()
    wholesale and the shared fixture refuses structured output.
  - run_stream_events became a context manager; the bare async generator mock
    kept working regardless.
  - end_strategy flipped early -> graceful, letting a previously-skipped tool
    call execute and hard-fail formula generation.
  - GoogleProvider(vertexai=True) was removed entirely.

The doubles now wrap real pydantic-ai types, one test drives the genuine
streaming path, one proves cancellation unwinds through the context manager,
and test_pydantic_ai_contract.py pins the API surface (public and private) so
the next upgrade fails at import rather than mid-run in production.

Verified: assistant + core/generative_ai 343 passed, 66 skipped; full backend
suite 11962 passed, 360 skipped, 1 failed. That failure
(test_view_empty_count_aggregation_for_interesting_table, BaserowFormulaButtonType
missing empty_query) is pre-existing and unrelated — the identical failure occurs
at base commit 321c00adc, and this branch changes nothing under
backend/src/baserow/contrib/ or premium/.

Note for future upgrades: _ErrorRecoveringStream in retrying_model.py
re-exposes each StreamedResponse class attribute as a delegating property,
because class attributes shadow __getattr__. V2 added state and metadata. That
list must be revisited on every pydantic-ai upgrade — the failure mode is a
wrong value, not an error.

* fix: give Google models a usable HTTP deadline

A bare httpx.AsyncClient defaults to a 5s timeout, and GoogleProvider
forwards that to the Gemini API as an explicit deadline, which the API
rejects because its minimum is 10s. Every Google model was therefore
unusable. Build the client with pydantic-ai's own
create_async_http_client factory instead (600s read, 5s connect).

Also document GOOGLE_API_KEY alongside the other assistant provider
keys, pass it through docker-compose, and bridge it in the eval
conftest so evals can target Gemini.

* fix: resolve GOOGLE_API_KEY explicitly for Google providers

_PROVIDER_ENV had no google entry, so _resolve_credentials fell through
to the deprecated UDSPY_LM_API_KEY and handed whatever it held (e.g. a
Groq key) to Google. It only worked because pydantic-ai reads
GOOGLE_API_KEY itself when no key is passed. Map all four google
prefixes explicitly, matching the other providers' precedence.

Also raise the title-generation timeout from 10s to 15s: 10s is exactly
Gemini's minimum allowed deadline, leaving no margin.
2026-08-20 12:20:40 +02:00
Davide Silvestri 667cfdd850 feat: support grouped row ordering (#5787)
* feat: support grouped row ordering

* fix: use existing endpoints without modifications

* fix: make grouped row moves reliable and optimistic

* address feedback
2026-08-20 10:48:05 +02:00
Davide Silvestri ad08d4be1d feat: Group-by aggregations (#5602)
* feat: show per-group aggregations in grouped grid views

Each group header shows the column's configured Summarize value computed
over that group's rows, column-aligned at every depth, visible whether
the group is collapsed or expanded. Reuses the footer aggregation config
and display components, and an interactive per-group picker that sets the
shared column aggregation. Gated behind the group_by_aggregations frontend
flag; backend returns values via the existing group-by-data response.

Not included (follow-up): realtime/live updates, performance and caching,
and consolidating the group-by-data and aggregations endpoints into one
request for grouped views.

* refactor: de-duplicate Decimal NaN handling in grid aggregations

Extract the repeated Decimal("NaN") -> "NaN" JSON-safety hack into a single
json_safe_aggregation_value helper, reused by the group-by per-group and totals
aggregations and the authed/public footer aggregation endpoints.

* fix: address copilot feedback on group-by aggregations

- Only show the "+ Summarize" picker for unconfigured columns; a configured
  column with no per-group value (e.g. distribution) now renders nothing
  instead of looking unconfigured.
- Document the aggregations_only and include_totals query params and the
  optional top-level aggregations field in the group-by-data OpenAPI schema.
- Mark row_count, sibling_index and row_offset optional (omitted in the lean
  aggregations_only mode).

* fix: de-flake replay-events last-seen-expired test

The test assumed RealtimeEvent id 1 never exists, but the id sequence isn't
reset between transactional tests, so the recorded event got id 1 when the
test ran first on an xdist worker and replay succeeded. Capture the real id,
delete it to simulate retention, and replay from it.

* feat: live, consolidated group aggregation updates

Group-header aggregation values and the footer total now update live and in
place on any change (cell edit, row create/delete, realtime), with no spinner.
In grouped mode they come from a single group-by-data request (aggregations_only
+ include_totals); the standalone /aggregations/ endpoint is no longer called
while grouped. Sort changes need no refresh (order-independent). Gated behind the
group_by_aggregations flag; flag-off behaviour is unchanged.

Deferred: per-group targeting (refreshes the loaded window), the optimistic +
realtime double request, and the 7.3.2 picker e2e.

* fix: dedupe and harden per-group aggregation refresh

Selecting an aggregation in a grouped view fired the group-by-data request
two or three times and could leave the footer total hidden behind a stuck
spinner until the page was refreshed.

- Clear the footer loading flag from refreshGroupByAggregations so the total
  shows on first select.
- Make refreshGroupByAggregations the single owner and supersede in-flight
  requests so a stale response can't overwrite newer values.
- Skip the duplicate fetch from updateFieldOptionsOfField and the footer
  watcher while a picker already owns the refresh.
- Right-align and shrink the banner aggregation value, and let the label slide
  behind the previous field instead of hiding it.

* chore: remove the group_by_aggregations feature flag

The per-group aggregations feature is finished, so enable it unconditionally
and drop the flag gating from the grid footer, group banners, and the
aggregation refresh action.

* test: drop obsolete group-by aggregation feature-flag specs

The group_by_aggregations flag is gone, so the two specs that asserted the
flag-disabled behaviour no longer apply.

* fix: stop the row context menu's Select row from clearing its own selection

The global click handler that clears a multi-select when clicking outside the
grid also fired for the row context menu's "Select row" click, wiping the
selection it had just made (most visible in group-by). Skip the clear when the
click lands inside a context menu; cell clicks, which should still clear, are
unaffected.

* fix: flaky test

* fix: show the spinner for updates as well

* fix: address copilot aggregation comment

* fix: avoid optimistic group aggregation values

* fix: address feedback

* fix: hide vert divider before primary field

* fix: only re-fetch when raw_aggregation_type changes
2026-07-06 08:20:54 +00:00
Davide Silvestri 0aa7147db3 Collapsible group-by grid view (#5470)
* feat: add collapsible group-by grid view

* fix: address copilot feedback, plus some other cleanup/fixes

* fix: harden grid e2e navigation

* Add e2e tests; improve performance; clean up code

* feat: show resolved values for reference fields in group-by headers

- Resolve collaborator, link-row and select group values to renderable display
  objects in the group-by data API, batched once per field per page (O(1) lookups,
  no per-group queries).
- Order many-to-many groups identically to the rows via correlated-subquery
  ordering, since the relation column is shadowed by the aggregated array
  annotation in group-by queries.
- Render the display values as chips in the group-by banner via dedicated
  multiple-select / multiple-collaborators components; shrink the collaborator
  badge, reduce the field-name size and keep the label on one line.

* fix: group many-to-many fields by their set of values

Grouping a grid by a collaborator, multiple-select or link-row field
produced empty groups with orphaned rows and duplicate headers for the
same set of values. The group key (an id array) was order-sensitive: the
backend's aggregated array order was unstable row-to-row and the cell
appends new values, so an optimistically-created group's key diverged
from the server's and rows were rejected by rowBelongsToGroupBySection.

- pathKey and the group-row Vue keys now sort m2m id arrays numerically,
  so a group is identified by its set of ids, not their order.
- The backend aggregates the group value ordered by related id and sorts
  the group's unique value, making grouping deterministic and set-based.
- Optimistically-emptied groups (row_count 0) are no longer rendered (the
  node is kept for reconciliation), and the leading group gap is fixed so
  the first visible group has no spurious gap.
- A newly created collaborator group resolves its badge name from the
  workspace store instead of requiring the name on the value.

* fix: keep cell multi-select when dragging in a group-by view

A multi-select drag ends with a click whose target is the rows
container (the common ancestor of the dragged cells). cancelMultiSelect-
IfActive cancels the selection unless that container is recognised as
part of the rows area, but its whitelist only knew the flat-grid classes
(grid-view__rows / grid-view__row). The collapsible group-by feature
renders rows in grid-view__group-by-rows containers, so the post-drag
click was treated as "outside the rows" and the selection was cleared on
mouseup. Add the group-by row containers to the whitelist.

* test: expect emptied group-by banners to disappear

The optimistic empty-group hiding (a group disappears once its last row
moves out) made the e2e contract that kept the emptied source group
visible at row_count 0 obsolete. Update the 2.2.7/2.4.4 assertions to
expect the emptied group's banner to be gone (new expectNoGroupByBanner
helper), and correct the tree-maintenance comments: the node is still
kept for reconciliation, but the layout no longer renders its banner.

* perf: load the collapsible group-by grid in one bounded request

Grouping a wide table by many fields took several seconds and a request
waterfall to render the first screen. The group tree was fetched one HTTP
request per depth, a budget that ran out before reaching any leaf forced
a per-parent fallback, and the rows endpoint resolved group-by metadata
unconditionally.

Backend
- Walk the descendant tree with one batched windowed query per group-by
  level (get_group_by_data_for_parents) instead of one query per parent,
  so a single include_descendants request returns the whole visible
  subtree in O(depth) queries.
- Scale the descent window to the viewport: row_budget = ceil(limit /
  depth). A deep group-by stacks each leaf row under its ancestor
  banners, so far fewer leaf rows fill the first screen; the window now
  returns a viewport-sized slice (~264 -> ~68 groups on a 12-level grid)
  and the rest lazy-loads on scroll.
- Gate the rows endpoint's group-by metadata behind
  include=group_by_metadata so it is not computed when unused.
- Resolve reference/link-row display values in one id__in query per field
  across all pages instead of once per page.

Frontend
- Initial load issues one group-by-data prefetch and one viewport rows
  request; expand mode no longer takes the per-depth path.
- Cap the banner indent (<=50px) and shrink the per-level arrow spacing
  as the group-by count grows, keeping the count aligned and the field
  name ellipsised; render multi-level loading skeletons for the
  not-yet-loaded levels.
- Guard walkPage against a cyclic page-resolution stack overflow and keep
  activeGroupBys filtered to fields that still exist.

Plus e2e env isolation (configurable ports, cookie prefix) and docs.

* fix: address review feedback

Addresses the review comments on the collapsible group-by grid PR.

- Gate the group-by add-row "+" on the same condition as the flat grid
  (not read-only, not a one-way data sync, has create-row permission), so
  it no longer renders buttons that error on click for data-sync tables.
- Show the "(Empty)" label for empty array-valued groups (multiple select,
  link row, collaborators), matching the text-field behaviour.
- Stop the flat-grid row placeholder from rendering in group-by mode
  (v-else-if instead of v-else).
- Render formula group-by headers via the result field type's group-by
  component instead of RowCardFieldFormula, removing the dev-only
  "Missing required prop: row" Vue warning.
- Keep the cell selected at the first/last field for both Tab and arrow
  keys (restore the pre-refactor behaviour); navigating past the edge no
  longer drops the selection in either flat or group-by mode.
- Re-enable and de-flake the "sorted add outside buffer" e2e test: assert
  on the re-resolved last row instead of a snapshotted renderedRowCount()
  index, which raced with the create-confirmation re-render in CI.

* fix: keep rows inserted below in a grouped grid view in their group

Insert-below and add-row in a grouped view now derive the new row's group
path from the neighbouring row, so it inherits all writable group-by values
and lands in the same group; `before` is set only when the next row shares
that group.

* feat: soft-cap adding group-bys at 5 in the view UI

Once a view reaches 5 group-bys the add button is disabled with a tooltip;
views that already have more keep working and only offer to remove them.

* limit group-bys; fix css

* refactor: polish code and comments

* fix: address Bram's feedback

* feat: add vertical gap between sibling sub-groups and indent banner labels with their chevron

* fix: address remaining feedback

* fix: row-coloring and fixed-height for add-row

* fix: address Bram's feedback v2

* fix regression in last commit

* fix: address grid group review comments
2026-07-03 09:09:52 +02:00
Davide Silvestri d8ff2e5b1f refactor: add a test plan and extract grid view helpers in preparation for collapsible group-by (#5430)
* refactor: extract grid view common test helpers

* refactor: extract row-lifecycle helpers and migrate grid store

Add computeRowInsertPosition to utils/row.js (expresses insert
position by row identity rather than flat array index).

Add handleRowCreated, handleRowDeleted, handleRowUpdated to
rowLifecycle.js. Each takes a store-supplied mutations adapter so
the decision logic (filter matching, sort position) is shared
between the flat-array grid store and the upcoming collapsible
group-by store.

Migrate createdNewRow, updatedExistingRow, deletedExistingRow in
grid.js to delegate through the new helpers via inline adapter
closures that translate position descriptors to the existing
flat-buffer Vuex mutations. Observable behaviour is unchanged;
search gating is preserved in each Vuex action.

Also includes grid view e2e test additions (section 1.5 task queue,
section 7.7 row identifier type, section 10.1 hover actions) and
grid test plan updates from the refactor/grid-view-common-e2e work.

* chore: fix CI

* chore: cleanup

* refactor: remove dead grid e2e search helpers and dedupe row-lifecycle guards

- Drop the unused openSearch/typeInSearch/clearSearch/toggleHideNotMatchingRows
  methods from GridPage; the richer, used variants live in
  grid_view_options.spec.ts. This also removes the placeholder/getByText
  selectors flagged in review (the remaining 'Delete row' selector stays scoped
  to the visible context menu).
- Centralize the repeated 'applyMatchFlags ?? noop' / 'rowsForMatchCheck ??
  emptyRows' guards into a single normalizeMutations() helper. No behavior change.

* refactor: remove dead updateMatchFilters/updateMatchSortings grid actions

Both grid store actions lost all production callers in the row-lifecycle
migration (match flags are now computed via onRowChange/reapplyMatchFlags and
direct computeRowMatchFlags calls). Repoint the remaining viewFilters test at
the live onRowChange path instead of the orphaned updateMatchFilters action.

* docs: note field-constraint create/edit coverage in grid view test plan

Add 1.6.x and 2.6.x TODO entries describing add/edit behavior under unique and
unique-with-empty field constraints (backend validation error surfaced +
optimistic rollback; empty values exempt from uniqueness).

* test: await route registration in failNextRequest

failNextRequest fired page.route() without awaiting it, so the intercept
could register after the caller already triggered the request. Make it async
and await registration before returning (mirroring pauseNextRequestWithSignal);
it now returns { done } and the 3 callers await it.

* test: scope grid_interaction serial mode per-describe

Replace the single file-level serial config with a per-describe one (matching
the other two grid specs) so a failure in one block no longer skips the rest and
independent blocks can run in parallel.

* docs: document createRowLifecycleContext and clarify escape wording

- Add a docstring to createRowLifecycleContext.
- Reword the Deferred/Escape note in the grid view test plan.

* fix(e2e): return created rows from createRows helper

setupGrid expected createRows to return the created rows to collect their
ids, but the helper returned void and discarded the batch-create response,
so created.map() threw 'Cannot read properties of undefined' and every
grid_interaction spec failed deterministically. Return response.data.items.

* revert publicView changes
2026-06-25 12:26:19 +00:00
Davide Silvestri 00c450872b chore: respect BASEROW_BACKEND_LOG_LEVEL setting in tests and management tasks (#5160)
* chore: respect BASEROW_BACKEND_LOG_LEVEL setting in tests and management commands

* fix: use dynamic Loguru {process} placeholder instead of baked os.getpid()

With setup_logging() now called from CoreConfig.ready(), the PID was
frozen to the parent process. Celery prefork children inherited the
wrong PID in their log output. Loguru's {process} resolves per record.

* fix: address feedback
2026-04-14 14:44:35 +02:00
Davide Silvestri cf15a4a02f refactor (MCP): refactor MCP tools; share AI Assistant capabilities (#4980)
* feat(mcp): refactor tools to service layer and add database/table/field CRUD

Replace internal API request pattern with a dedicated service module for
MCP operations. Simplify tool architecture from dynamic per-table tools
to static tools with explicit table_id parameters. Add new tools for
managing databases, tables, fields, and batch row operations.

* fix(mcp): address Copilot review feedback

- Let exceptions propagate from MCPTool.call() so call_tool() logs them
- Fix N+1 queries in get_table_schema using enhance_field_queryset hook
- Fetch fields for all tables in a single specific_iterator pass
- Clamp list_rows pagination to safe bounds (ROW_PAGE_SIZE_LIMIT)
- Fix update_fields docstring to reflect type-change support
- Fix module path in utils.py comment
- Update "Adding a new tool" docs to match current MCPTool pattern

* fix: comment risky tools; waiting for a proper permission check

* feat(mcp): add enabled flag to MCPTool and disable risky tools

Add `enabled` attribute to MCPTool base class so tools can be registered
but hidden from MCP clients. Disable database/table/field CRUD tools
until users can control tool availability through the UI.

Also add docs/testing/mcp-test-plan.md with manual testing instructions.

* fix(mcp): replace list[dict] with typed Pydantic models for field/row specs

Validate required keys (name+type for field create, id for field update,
id for row update) at the schema level instead of relying on KeyError
from dict.pop() in the service layer.

Uses extra="allow" so type-specific options and field values pass through.

* fix: wrap update_rows in a transaction

* address feedback
2026-04-01 08:52:59 +00:00
Davide Silvestri 40c9f48081 feat (assistant) 3/3: add themes to templates and a set_theme tool (#4970)
* feat(assistant): add theme catalog, apply_theme, and theme templates

Add 20 new theme templates and theme infrastructure:
- THEME_CATALOG with 22 themes, ThemeName type, _load_theme_data(), apply_theme()
- BuilderItemCreate.theme field with auto-apply on creation
- set_theme() tool for changing themes on existing applications
- Unit tests and eval tests for theme functionality

* refactor(assistant): migrate theme evals to EvalChecklist pattern

Replace removed assert_no_tool_errors with EvalChecklist + count_tool_errors
in test_agent_creates_app_with_theme and test_agent_changes_theme. Remove
stale test_navigate_to_workspace test.

* refactor(assistant): move theme code from core/types to builder/themes

Theme catalog, apply_theme, and related helpers are a builder concern,
not core. Move them to tools/builder/themes.py so core never imports
from builder. Also make apply_theme return bool so set_theme can report
errors instead of silently claiming success, and fix "Thank youb" typo
across all 23 theme templates.

* refactor (AI field): remove langchain and use pydantic-ai (#5017)

* refactor(ai): replace langchain with pydantic-ai for LLM calls and structured output

Replace langchain dependency with pydantic-ai as the LLM abstraction
layer. Each GenerativeAIModelType now implements get_ai_model() returning
a pydantic-ai Model instance, and the base class provides prompt() and
prompt_structured() using Agent.run_sync().

- Remove langchain, langchain-openai, and direct openai/anthropic/mistralai
  deps (pydantic-ai-slim extras install them)
- Add prompt_structured() with PromptedOutput for Pydantic model output
  (e.g. BaserowFormulaModel)
- Add output_choices parameter to prompt() for constrained choice selection
  with fuzzy matching, compatible with all models including those without
  tool support
- Remove custom output_parsers.py (StrictEnumOutputParser, JsonOutputParser
  replacements)
- Update AI field job flow to use prompt(output_choices=...) for choice
  output and prompt_with_files fallback for file-based prompts

* refactor(ai): replace deprecated Assistants API with pydantic-ai multi-modal content

Replace OpenAI's deprecated Assistants API (file_search, threads, polling)
with pydantic-ai's native BinaryContent support. Files are now read from
storage and passed directly in the prompt as multi-modal content — no
upload/delete lifecycle needed.

- Add content parameter to prompt() for multi-modal file attachments
- Remove GenerativeAIWithFilesModelType abstract class and its upload/
  delete/prompt_with_files methods
- Remove get_client() from BaseOpenAIGenerativeAIModelType (no longer
  needed without file operations)
- Replace AIFileManager.upload_files_from_file_field() with
  get_file_contents() returning BinaryContent objects
- Simplify job_types.py: file+choice paths merge into single prompt()
  call with content and output_choices parameters
- Remove format_prompt/parse_output hooks (no longer needed)
- Remove FileId type alias and AIFileError exception
- Works with any provider that supports documents (OpenAI, Anthropic,
  Mistral, Google) instead of only OpenAI

* refactor(ai): unify prompt API into single method with output_type parameter

Merge prompt_structured() into prompt() via the output_type parameter:
- None (default): plain text response
- list[str]: choice selection with fuzzy matching
- Pydantic BaseModel/TypedDict: structured output via PromptedOutput

Remove prompt_structured(), output_choices parameter, and dead code
(format_prompt, parse_output hooks, AIFileError, FileId type).

* refactor(ai): clean file handling API with model type owning processing logic

Redesign file handling so the model type owns all file processing decisions
(embed vs upload, size limits, count limits) while the manager only reads
metadata from storage and provides a lazy reader callback.

- Add supports_files flag and prepare_files() to GenerativeAIModelType base
- OpenAI implementation: embeds images inline (BinaryContent, 50MB/500 limit),
  uploads documents (UploadedFile via Responses API)
- Use OpenAIResponsesModel instead of OpenAIChatModel for OpenAI provider
  (supports all file types via input_file/input_image)
- AIFileManager.prepare_file_content() collects metadata, passes lazy
  read_file callback — no data read until model type requests it
- Remove is_file_compatible/get_max_file_size from public API (moved into
  prepare_files)
- Add type hints throughout

* fix(assistant): fix generate_formula tests and grid view row_height

- Add output_type param to TestGenerativeAIModelTypePromptError.prompt()
- Return BaserowFormulaModel in test mocks instead of raw JSON string
- Use correct ORM field name row_height_size in grid view from_django_orm

* docs: add AI field test plan

* refactor(ai): improve docstrings, fix prompt signature and empty prompt handling

* refactor(ai): merge ERROR_OUTPUT_PARSER into ERROR_GENERATIVE_AI_PROMPT

The distinction between output parsing errors and prompt errors didn't
provide actionable info to the user. Both now surface as a single
ERROR_GENERATIVE_AI_PROMPT error code.

* refactor(ai): move value generation into AIFieldHandler with AIFile abstraction

Introduce AIFile dataclass that wraps serialized UserFile dicts with
lazy read_content(). Move the core generation logic from
AIValueGenerator._generate_value_for into AIFieldHandler.generate_value_with_ai
so the handler owns the full flow: prompt resolution, file preparation,
AI call, file cleanup, and choice resolution.

- prepare_files() now takes list[AIFile] and returns only processed files
- cleanup_files() mirrors prepare_files() for provider file cleanup
- delete_file() takes AIFile instead of raw file_id string
- AIFieldEmptyPromptError raised when prompt resolves to empty
- Delete AIFileManager (absorbed into handler + model type)

* docs: add AI field architecture overview

* fix(ai): handle missing files and partial upload cleanup in prepare_files

- OpenAI prepare_files() now catches per-file errors (missing files,
  upload failures) and skips them instead of failing the whole generation
- Handler cleanup uses ai_files instead of prepared so files uploaded
  before a mid-prepare failure are still cleaned up

* fix(ai): normalize LLM responses before choice matching

Strip quotes, markdown bold, backticks, and trailing punctuation from
model responses before fuzzy matching. Use case-insensitive comparison
so responses like "POSITIVE" correctly match "Positive".

* address feedback

* Address feedback
2026-04-01 10:41:10 +02:00
Davide Silvestri b65c7e77cb chore refactor (AI Assistant): context offloading; better telemetry data; add google and anthropic models compatibility (#4951)
* chore(deps): replace udspy with pydantic-ai and opentelemetry-sdk

Replace the udspy dependency with pydantic-ai-slim (with openai, groq,
anthropic, bedrock providers) and opentelemetry-sdk for structured
telemetry collection.

* fix(sentry): exclude pydantic_ai from auto-enabling integrations

sentry-sdk's pydantic_ai integration patches ToolManager._call_tool
which was removed in pydantic-ai >= 1.x (now execute_tool_call),
causing import-time errors.

* feat(settings): add dev log file mirroring and allow embeddings URL in tests

- Add BASEROW_LOG_FILE support in dev settings to mirror logs (including
  loguru output) to a file, useful for AI-assisted debugging.
- Allow BASEROW_EMBEDDINGS_API_URL to be overridden via env in test
  settings for search_user_docs eval tests.

* feat(assistant): add message_history field to AssistantChat

Add a BinaryField to store serialized pydantic-ai message history
(JSON bytes) for multi-turn conversation context, replacing the
previous udspy-based conversation state.

* refactor(assistant): port to pydantic-ai agent framework

Replace udspy with pydantic-ai as the agent framework for the AI
assistant. Key changes:

- Add Agent definitions with typed deps (AssistantDeps) and dynamic
  toolsets for runtime tool loading
- Add deps module with AssistantDeps, ToolHelpers, and EventBus for
  streaming events to the UI
- Add history module for serializing/deserializing pydantic-ai message
  history to the database
- Add model_profiles for provider-specific configuration (Anthropic,
  OpenAI, Groq, Bedrock)
- Add toolset module with ToolGroup base class replacing the udspy
  tool registry pattern
- Add shared/ with formula_utils and sub-agent helpers
- Add tool_types.py per tool module for pydantic-ai ToolDefinition
- Port all tool modules (core, database, navigation, automation,
  search_user_docs) from udspy decorators to pydantic-ai Tool instances
- Port assistant orchestrator, handler, and prompts
- Remove signatures.py (replaced by pydantic-ai output types)

* refactor(assistant): update telemetry for pydantic-ai

Rework telemetry collection to use pydantic-ai's message history
format and OpenTelemetry SDK for structured span/event recording,
replacing the previous udspy-based telemetry hooks.

* test(assistant): update unit tests for pydantic-ai port

Rewrite assistant unit tests to use pydantic-ai's testing utilities
(TestModel, FunctionModel) instead of udspy mocks. Add new test files
for core tools, navigation tools, and search docs tools. Remove
obsolete skip file.

* test(assistant): add LLM eval test suite

Add end-to-end eval tests that run the real agent against a live LLM
to verify tool selection, schema compatibility, and output quality.

Includes evals for: navigation, core builders, database tables/rows,
sample rows, automation workflows, search_user_docs, and cross-cutting
structured output validation.

Tests are marked with @pytest.mark.eval and skipped by default.
Configure via EVAL_LLM_MODEL or EVAL_LLM_MODELS env vars.

* docs: add eval guide and update AI assistant installation docs

- Add docs/development/ai-assistant-evals.md with instructions for
  running the eval suite, configuring models, and writing new evals.
- Update docs/installation/ai-assistant.md to reflect pydantic-ai
  provider configuration replacing the previous udspy setup.

* fix(assistant): fix test patch paths, optional filter args, and eval marker

- Fix mock patch paths from `assistant.agent` to `assistant.agents`
- Make ListTablesFilterArg fields optional to prevent LLM validation errors
- Surface field_errors in create_fields tool result
- Simplify EvalToolTracker to use message history inspection
- Register `eval` pytest marker and skip evals by default

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: move testing docs to docs/testing/ and add PR test plan

Move ai-assistant-evals.md from docs/development/ to docs/testing/,
add ai-assistant-test-plan.md with manual and automated test steps
for the pydantic-ai port PR.

* refactor(assistant): extract row models to types/rows.py, rename utils to helpers

- Move FieldDefinition, row model builders, and get_link_row_hints to
  new types/rows.py module with dict-of-callables dispatch replacing
  match/case
- Simplify update model: fields are optional (omit = don't change),
  removing the __NO_CHANGE__ sentinel
- Move get_table_rows_tools into tools.py as _build_row_tools since it
  builds pydantic-ai Tool objects
- Rename utils.py to helpers.py for clarity, remove dead list_tables
- Add docstrings with :param/:returns to all public functions, add
  proper type annotations throughout

* refactor(assistant): flatten field/view/filter types into single models

- Replace per-type config classes in fields.py with a single flat
  FieldItemCreate model using optional type-specific fields and a
  model_validator for type aliases
- Simplify view_filters.py and views.py type hierarchies similarly
- Update table.py types and corresponding tests

* fix(assistant): improve telemetry span processor and minor tweaks

- Replace SpanExporter with SpanProcessor for real-time span handling
- Remap child tool spans past 'running tools' grouping span
- Parse JSON string arguments in tool call parts
- Add data_brief parameter to sample rows prompt
- Disable reasoning_effort for groq models temporarily
- Rename _fix_formula to _fix_formula_field in helpers

* refactor(assistant): use ISO strings for dates and add dateutil fallback

Replace Date/Datetime Pydantic model objects with compact ISO 8601
strings. Add lenient parsing via dateutil.parser fallback when
fromisoformat fails.

* feat(assistant): add DO/EXPLAIN agent modes with switch_mode tool

Introduce AgentMode enum (DO/EXPLAIN) and ModeAwareToolset that filters
available tools based on mode. DO mode (default) exposes all action
tools except search_user_docs. EXPLAIN mode exposes only read-only
tools (list_*, navigate) plus search_user_docs for answering Baserow
feature questions. The switch_mode tool allows bidirectional switching.

* refactor(assistant): flatten automation node types and add $formula: convention

Replace 13+ per-type action node classes (RouterNodeCreate, SendEmailActionCreate,
etc.) with a single flat ActionNodeCreate model using @model_validator for per-type
validation and dict-dispatched functions for ORM conversion and formula generation.

Add $formula: prefix convention — values prefixed with '$formula:' are sent to the
LLM formula generator, plain values become literal formulas. Also detect raw formula
expressions (get(), concat(), etc.) written inline.

Add trigger validation: periodic triggers now require periodic_interval (with
automatic folding of flat fields), row triggers require rows_triggers_settings.

* build: bump pydantic-ai-slim to 0.1.66 and anthropic to 0.84.0

* feat(assistant): add RetryingModel for transient provider error recovery

Wraps pydantic-ai model instances to automatically retry on transient
errors (rate limits, timeouts, server errors) with exponential backoff.
Handles both streaming and non-streaming calls.

* feat(assistant): add AgentMode system with ModeAwareToolset and switch_mode

Introduce domain modes (DATABASE, APPLICATION, AUTOMATION, EXPLAIN) that
control which tools are visible to the agent. ModeAwareToolset filters
the combined toolset per-mode, registries generate per-mode manifests,
and switch_mode lets the agent transition between domains. Each mode
gets a cross-mode summary so the agent knows what other modes offer.

* refactor(assistant): integrate RetryingModel, event-based streaming, and JSON retry

Replace direct model usage with RetryingModel for resilience. Rewrite
streaming to use run_stream_events for proper text/reasoning/tool event
handling. Add JSON-tool-call-as-text detection with automatic retry.
Auto-detect starting mode from UI context. Update model_profiles with
max_tokens settings.

* refactor(assistant): improve shared formula utils and add formula language reference

Add RAW_FORMULA_RE for detecting raw formula expressions, needs_formula()
for $formula: prefix and raw formula detection, literal_or_placeholder()
for ORM value creation, and a shared formula language prompt. Improve
formula generator to track remaining unresolved fields across retries.

* refactor(assistant): improve database tools with routing rules and type fixes

Add per-module routing rules via get_routing_rules(). Extract ToolInputError
to helpers. Fix field type validators, improve row model handling, and
refine view filter types. Update agents and prompts for better tool
guidance.

* refactor(assistant): improve automation tools with routing rules and formula handling

Add per-module routing rules for automation. Improve node type handling
with better formula context support. Refine automation agents and prompts.

* fix(assistant): improve telemetry span processor with real-time remapping

Enhance SpanProcessor with JSON arg parsing, real-time span remapping,
and improved trace output handling. Update tests to cover new behavior.

* test(assistant): update tests for mode system, retry logic, and type refactors

Add tests for switch_mode, mode-aware manifests, JSON retry logic.
Add test_assistant_automation_node_tools and test_assistant_database_field_tools.
Update existing database/automation/core tests for refactored types and
new tool signatures. Update eval_utils for new deps structure.

* fix: lint

* chore(frontend): ignore .claude dir in vite watcher and fix Nitro EMFILE

- Add .claude/ to vite server watch ignore list alongside node_modules
  and .git to avoid unnecessary file watching in worktrees.
- Configure Nitro devStorage to use fs-lite driver to prevent chokidar
  from watching the entire repo root, which causes EMFILE on macOS in
  large monorepos.

* fix(tests): fix test settings and seat usage test isolation with xdist

- Ensure pytest always finds backend/pytest.ini by passing -c pytest.ini
  explicitly, fixing DJANGO_SETTINGS_MODULE=dev when running from root
- Preserve existing TEST dict keys when setting MIGRATE in test settings
- Add transaction=True to seat usage tests to prevent data leaking from
  TransactionTestCase tests running on the same xdist worker

* fix(assistant): fix field types, formula regex, validator guard, and consolidate evals

Fix multiple_select returning None instead of [], link_row description
typo, formula regex missing greater_than_or_equal/less_than_or_equal
variants, and guard against overwriting original validators on repeated
prepare_tools calls. Consolidate sample rows and navigation evals into
the database tables eval file and remove the meta tool-call history test.

* fix(assistant): improve tool return types, filter aliases, and eval infrastructure

- Return consistent dict types from all tools instead of plain strings
- Add operator aliases for view filters so LLMs can use natural names
- Fix boolean filter operator (is → equal)
- Remove reasoning format from UTILITY model profiles (pollutes structured output)
- Add ModelRetry for workflow creation and formula agent errors
- Add EvalChecklist for soft assertions with pass/fail scoring
- Add EVAL_RETRIES support for flake detection in eval tests
- Suppress loguru DEBUG noise during evals

* refactor(assistant): extract table creation helpers and remove unused model profile

- Extract _create_empty_tables and _create_table_fields from create_tables
- Filter out duplicate primary field in field creation to avoid model mistakes
- Remove unused gpt-oss-20b model profile
- Always attempt sample rows regardless of field errors

* fix(assistant): strip <think> tags and unify streaming as reasoning chunks

Models like MiniMax-M2.5 emit <think>...</think> tags inline. Handle
ThinkingPart/ThinkingPartDelta events from pydantic-ai and extract
inline thinking from text parts as a fallback. Stream all content as
AiReasoningChunk during the agent run; the final answer is emitted
as AiMessageChunk by _emit_answer.

* fix(assistant): simplify streaming and add collapsible reasoning UI

Replace _accumulate_text/_extract_thinking with a single _get_content_delta
helper that forwards text/thinking deltas. Accumulate reasoning_so_far and
strip <think> tags before sending to frontend (which replaces content on
each chunk). Add collapsible reasoning bubble (max 250px with fade mask
and chevron toggle).

* fix(assistant): bridge legacy UDSPY_LM_* env vars to pydantic-ai config

* docs(assistant): improve ai-assistant.md and add AWS_REGION_NAME backward compat

- Add both Bedrock auth methods (boto3 creds + bearer token)
- Add section 6 with pydantic-ai model overview link and provider list
- Restructure migration table: unchanged / bridged / new variables
- Fix AWS_BEARER_TOKEN_BEDROCK incorrectly listed as removed
- Bridge AWS_REGION_NAME to AWS_DEFAULT_REGION in settings for backward compat

* minor doc/evals fixes

* fix(assistant): strip unclosed <think> tags during streaming

Models behind Groq emit <think> tags as text content rather than using
the native thinking protocol. During streaming, the closing </think>
tag may not have arrived yet, causing raw thinking content to leak to
the frontend. Also strip think tags from tool thought fields and reset
reasoning on tool results.

* docs(assistant): use provider:model format and refresh eval docs

- Update all docs to use pydantic-ai provider:model format (colon separator)
- Fix mixed-up provider descriptions in configuration.md
- Refresh eval docs: replace assert_no_tool_errors with EvalChecklist pattern
- Add embeddings URL for local vs Docker in ai-assistant-evals.md
- Skip KB sync post_migrate signal during tests
- Fix temperature type in model_profiles.py
- Refactor justfile PYTHONPATH for test recipe

* fix(assistant): clean up navigation and improve tool types

- Remove unused WorkspaceNavigationRequestType
- Narrow exception catch in navigate tool to ObjectDoesNotExist
- Guard id field in CreateRowModel.from_django_orm
- Use id__in for batch filtering in ListTablesFilterArg

* Revert "chore(frontend): ignore .claude dir in vite watcher and fix Nitro EMFILE"

This reverts commit 4be1be19d2.

* fix: ai-assistant-test-plan.md tool smoke test prompt for list_builders

* fix: Posthog env var names in docs/testing/ai-assistant-test-plan.md

* fix: wrong doc reference
2026-03-20 10:53:17 +00:00