Commit Graph
9 Commits
Author SHA1 Message Date
alamin-br 440a949339 fix(assistant): stop Kuma runs failing on dropped DB connections and tool errors (#6517)
* fix(assistant): stop Kuma runs failing on dropped DB connections and tool errors

Kuma runs failed on dropped DB connections, link fields to non-text primaries and taken page paths, which made up most production failures.

* fix(assistant): address review on Kuma run failures

Health checks for DATABASE_URL configs, readable link examples without DISTINCT, a reused /login page, and error telemetry without provider bodies.

* fix(assistant): address second review on Kuma run failures

Login form set up on any reused /login page, lighter link examples, no refusal text in telemetry, guarded nested toolsets and title cleanup that keeps title characters.
2026-10-28 17:34:34 +01:00
Davide Silvestri 91fabcb3ab fix(assistant): let Kuma change menu items by uid instead of recreating them (#6295)
* fix(assistant): keep the menu items Kuma resends instead of recreating them

Kuma rebuilt every menu item as a new link with a new uid, so updating a menu deleted the click actions and settings of the items it meant to keep. Items matched by name now keep their uid, type, settings and children.

* fix(assistant): keep Kuma's menu items by uid instead of by name

list_elements now shows each menu item's uid, with sub-links nested
under their parent, and update_element takes the uid back for every
item Kuma keeps. A kept item keeps its type, settings, click actions
and sub-links; a new name renames it and a new page moves a link,
clearing the old page's parameters. children edits the sub-links.

Requests the menu can't apply are refused before anything is saved:
a page on a button, an unknown or repeated uid, or a new item named
like an item being removed, which means Kuma forgot its uid.

* test(assistant): set a non-default variant in the menu round-trip test

* test(assistant): add evals for Kuma's header menu edits

Five kuma-builder cases start from a header menu with a link, a
dropdown, a separator and a button with a click action, the kinds of
items production menus had when Kuma rebuilt them as page links. Each
checks that the items Kuma doesn't change keep their uid, type and
click action: adding a link, renaming the button, removing a sub-link,
making the button open a page, and adding pages one at a time.

The checks are tested against the untouched menu, the right edit and a
rebuild into page links.

* fix(assistant): delete menu items only when Kuma lists them

update_element takes remove_menu_items, the uids of the menu items to
delete. Every current item must come back in menu_items with its uid or
be listed there, so an item Kuma forgets is refused with its name and
uid instead of being deleted. remove_menu_items alone deletes those
items and keeps the rest. The rule also covers a forgotten uid, so it
replaces the check on new items named like removed ones.

* fix(assistant): ask Kuma for the whole menu when it changes one item

"Nothing is deleted unless listed" read to Kuma as permission to send
only the item it changed, which the tool then refused for leaving the
others out. The description now asks for every current item plus the
new ones, and points deletions to remove_menu_items.

* refactor(assistant): share uid helpers and let after_update add result keys

Prepares menu items to follow the table column pattern: canonical_uid and NO_CHANGES move to types/changes.py, the menu listing helpers move to types/menu_items.py, and an element type's after_update hook can now add keys to update_element's result.

* refactor(assistant): merge menu item changes like table column changes

merge_menu_items turns add, update, reorder and remove lists into the full item list core saves. Items it doesn't name are resent as saved, removing a dropdown removes its sub-links, and anything it can't apply is refused before saving, including pages of another application. name_key and unique_in_order are now shared with the table column merge.

* fix(assistant): let Kuma change menu items with add, update, reorder and remove lists

update_element on a menu, header or footer now takes add_menu_items, update_menu_items, reorder_menu_items and remove_menu_items by uid, like table columns, instead of the whole menu. Items Kuma doesn't name stay as saved, the result lists the menu's items after the write and the removed items, and a refused change saves nothing. A header or footer changes the menu nested inside it and refuses when it holds several.

* test(assistant): add evals for reordering menu items and removing a dropdown

Two kuma-builder cases on the header menu scenario check that moving Help keeps every item, its click action and the Products sub-links, and that removing the Products dropdown removes its sub-links and nothing else.

* fix(assistant): warn that undo keeps removed menu items deleted and list custom link urls

Undo restores no menu item change, so the tool now says so next to remove_menu_items, as it does for table columns. list_elements shows a custom link's url, so it no longer looks like a link to nothing. A header's or footer's menu is locked before its items are read.
2026-10-12 09:27:31 +02:00
Davide Silvestri eeb8d3900b fix(assistant): let Kuma change table columns by uid instead of replacing them (#6296)
* fix(assistant): keep the table columns Kuma resends instead of recreating them

Replacing a table's columns gave every column a new uid, which deleted the click actions of button columns, and adding or removing columns reset the styles of the kept ones. Columns matched by name and type now keep their uid and styles.

* test(assistant): add eval cases for editing table columns

* fix(assistant): don't run a call the argument fixer repaired by dropping values

A repair that left out a value the model sent used to run the tool anyway, so an edit could be ignored while the call reported success. The model now gets the error report plus the dropped paths and values instead. Moving a value, renaming a key and converting its type still run because the value survives. The harness lifecycle test now repairs a renamed key instead of replacing an unparseable value.

* feat(assistant): show table columns in Kuma's list_elements

* fix(assistant): let Kuma change table columns by uid instead of replacing them

* feat(assistant): let Kuma bind table columns to database fields

* fix(assistant): send unrepairable arguments back with the model's own errors

Check a repair for dropped values before validating it, and answer a repair
that still fails with the errors of the arguments the model sent. Arguments
whose only errors are unknown keys holding values go back without a repair,
the fixer may drop only empty unsupported keys, and arguments too deeply
nested to compare go back instead of raising.

* fix(assistant): show list field values in table columns and refuse type changes

Derive the path a column reads from the shape of the field's values, as the
table editor does, so lookups and array formulas show their values instead of
raw JSON, and refuse fields that hold files. Accept the type list_elements
shows in a column update but refuse a different one, and tell Kuma never to
remove a column to rebuild it.

Also: a value spelled differently from the stored formula keeps it as stored,
tables that list a property refuse field bindings, refusals name every
offending column, list_elements shows a table's data_source_id, and an unknown
data source ref is refused with a next step.

* test(assistant): check every kept table column and the reading of the link case

builder/edits-table-columns now compares Email and Edit with the seed apart
from Email's position. builder/keeps-link-column-settings requires that Kuma
read the columns with list_elements and allows two refused attempts, since
the columns' state decides the case. The edit-action lookup is shared.

* test(assistant): don't depend on the recursion limit in the nested JSON guard test

* refactor(assistant): move table column handling into element type hooks

* fix(assistant): recover tool calls the model printed as text

* refactor(assistant): move the remaining per-type update steps into element type hooks

* fix(assistant): don't complete a printed tool call cut off after a stray quote

* test(assistant): make the unknown-tool case reach the tool check
2026-10-08 13:26:26 +02:00
Davide Silvestri dc62052c97 [4/4] test: harden assistant evals and tool contracts (#6007)
* test: bring Kuma eval baseline and dataset updates from #6006

* test: harden assistant evals and tool contracts

Add production-replay datasets, resilient eval execution and comparison UI, a committed baseline, and broad tool contract and chain coverage on top of the runtime behavior changes.

* test: align tool contracts with #6006 list_tables and permission output

* fix: restore the eval runner results tab and pin it structurally

The Results tab shipped unable to execute: the closing brace of usageCell
was dropped, renderResults read an undeclared totals, the cost cell still
called the old four-argument usageCell, and a second pane clear wiped the
dataset errors appended just above it. Two tests covered the tab by
asserting substrings of the page, so all four passed against dead script.

Check the page structurally instead, with a small tokenizer, because the
backend CI image has no JavaScript engine and a node-based test would
silently skip there. Replace the sampled tool-visibility assertions with
the full routed-tool map, so adding a tool has to state its reach rather
than inherit one.

* test: score eval checks against the call that actually ran

An incomplete cross-mode call is answered with a re-call redirect, so the first create_workflows call can hold a pre-switch guess rather than the arguments that executed. Score the executed call instead, recognising the redirect through the router's own helper in both its retry and tool-result forms.

* test: score the update_row target from the database, not the first draft

The check read row_id out of the recorded create_workflows arguments,
which are the model's raw output. When those arguments fail validation
the toolset's argument-repair agent fixes them and the tool runs with the
repaired payload, so a workflow that correctly names its row still scored
as missing one. Measured over ten repetitions this produced one false
failure; the trace shows execute_tool succeeding and a fix_agent span
right behind it.

Read the persisted service instead, like the neighbouring trigger and
action checks already do.

* test: check saved values in the prod-replay evals

Replay checks now verify the form collects the order fields, the page was inspected, the requested tables have rows, ISO week numbers and signed amounts are correct for seeded rows, no broken formula is left behind, and all 30 employee rows carry typed values.

* fix: compare eval results only across the same case population

A baseline captured on an older dataset version ran a different set of cases, so its means are not comparable. The Results tab now requires the experiment and baseline to share a dataset version and says when they do not.

* test: expect Kuma to ask when an implied app table is missing

#6006 decided that a request to show records refers to workspace data, so Kuma asks where the projects come from instead of inventing a table. The eval had been flipped to expect building; restore the ask expectation while the explicit example-app case still builds.

* test: accept date subtraction as a correct date-difference answer

Subtracting two date fields returns a duration (verified: 5 days for 2026-01-01 to 2026-01-06), so an answer that subtracts the dates is correct even when it does not name date_diff. Retrieval rarely surfaces the reference-guide passage for date_diff, which made this case fail three times in four on an accurate answer.

* test: expect Kuma to offer a sample-data table when app records are missing

When no table holds the records an app should show, Kuma should create nothing and ask, offering a table with sample data among the next steps.

* test: accept a plain-text question when Kuma must ask

ask_user only records a question for the final answer, so a run that asks in its reply and builds nothing behaves the same for the user. The ask checks still require that nothing was created.

* test: match docs keywords through Markdown emphasis

Answers bold feature names, so '**File** field' missed 'file field'. Keyword matching now ignores emphasis markers, and the OCR case accepts 'AI prompt', the field type's name in the product.

* chore: recapture the Kuma eval baseline on the final stack

Three repetitions of all 122 cases on 3ca6497591 with Groq GPT-OSS 120B (harness v5): 355/366 passed. Docs 192/192, core 9/9, database 61/63, builder 55/60, automation 20/21, prod-replay 18/21.

* chore: drop an import the develop rebase left unused

* test: expect docs search in every mode

* test: require complete tracker and employee replay data

* fix: compare Kuma eval results using recorded cases and checks

* fix: correct Kuma eval scoring and preserve baseline runs

* test: reuse the seeded user in Kuma builder contracts

* test: isolate async docs-search database fixtures

Create users and workspaces in synchronous pytest fixtures so their writes stay inside the rollback transaction. Async setup previously used a separate autocommit connection and leaked users, causing later data-sync tests to fail on duplicate usernames.

Remove the global async-safety bypass, enforce Django's guard locally, and keep the real database hybrid test synchronous around its async tool call.

Verified the seeded two-test reproduction fails before and passes after with no leaked users. All 71 focused tests and 1,742 broader tests pass; one existing test is skipped. Scoped pre-commit checks pass.

* docs: update Builder eval count after rebase

* fix: grade saved assistant results and preserve eval errors
2026-10-01 09:18:04 +02:00
Davide Silvestri 7d94a86406 chore(deps): upgrade pydantic-ai to 2.50.0 (#6173)
* chore(deps): upgrade pydantic-ai to 2.50.0

- Bump pydantic-ai-slim 2.28.0 -> 2.50.0 and
  openinference-instrumentation-pydantic-ai 0.1.20 -> 0.1.27; the lock
  also moves anthropic to 1.8.0, openai to 3.19.2, google-genai to 2.25.0.
- Unwrap SourcedInstruction entries in the eval prompt override.
- Show the error message, not the model response dump, for
  UnexpectedModelBehavior errors.
- Disable the pydantic-ai first-run Logfire banner.
- Stop in-flight tools when an eval case times out.

* fix: address AI dependency upgrade feedback
2026-09-25 15:35:33 +00:00
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 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 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 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