34 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 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
Petr Stříbný 3cd690d72f Vendor advocate (#4704) 2026-02-10 17:17:28 +01:00
Petr Stříbný 0a665fcb27 Upgrade backend deps with Django 5.1 (#4550) 2026-01-23 10:00:31 +01:00
dimmur-brw a2fc6da7f6 Add ability to defer signals/tasks in tests (#4375) 2025-12-08 06:15:24 +01:00
Bram 336350bc71 Make read/write DB routing consistent for http requests and background tasks (#4077)
Make  read/write DB routing consistent for http requests and background tasks
2025-11-26 13:07:09 +01:00
Bram 4a9d4ec334 Workspace search (#4076)
Adds ability to search various items in workspace
2025-10-22 20:09:40 +02:00
Przemyslaw Kukulski a3ab4f7843 FeaturesNotAvailableError is raised when running a periodic data sync 2025-07-31 10:57:44 +00:00
Przemyslaw Kukulski a30bf63524 Field value constraints: Unique with empty 2025-07-08 05:03:04 +00:00
Przemyslaw Kukulski 5a156f64e3 Import and export workspace applications 2024-11-11 10:50:20 +00:00
Davide Silvestri 1ad62d4add ⏳ [1/4] Timeline view: backend view type and endpoint 2024-09-26 15:21:41 +00:00
Bram Wiepjes 1298aa7eec AI field 2024-04-02 19:50:44 +00:00
Davide Silvestri 55f43b59d8 1️⃣ Autonumber: Add field type 2023-12-13 08:48:58 +00:00
Davide Silvestri aa9a793dbe Resolve "Created by field type" 2023-12-11 10:02:00 +00:00
Petr Stribny 232c5eb6d2 Split field conversion tests 2023-11-29 11:23:19 +00:00
Petr Stribny a74a5f56f5 Resolve "Last modified by field" 2023-11-22 17:16:22 +00:00
Petr Stribny a8940f2887 Resolve "Real-time support for row change history" 2023-10-16 08:01:49 +00:00
Davide Silvestri 5248c21fc5 Resolve "Backend for row change history (v1)" 2023-08-25 13:16:39 +00:00
Petr Stribny 0892857ab5 Resolve "Calendar view" 2023-03-28 14:10:35 +00:00
Nigel Gott 2bbb22be2f Resolve "Export useful opentelemetry metrics." 2023-03-03 16:58:45 +00:00
Petr Stribny 5c7e654678 Resolve "Personal views" 2023-01-27 15:45:11 +00:00
Nigel Gott f81da4181e Add wildcard feature flag and change RBAC ones from nonspecific WIP to RBAC. 2022-12-19 10:40:49 +00:00
Davide Silvestri 87960cb885 Resolve "Fix the refresh_token for longer user sessions" 2022-10-27 09:45:34 +00:00
Jeremie Pardou-Piquemal 2f34b99fb9 Add enterprise plugin 2022-09-22 10:00:59 +02:00
Petr Stribny 1dc464461f Add Multiple Collaborators field 2022-09-06 15:32:12 +00:00
Davide Silvestri b6cd52eae2 Resolve "Undo / redo bundle multiple actions in a single undo / redo call" 2022-07-18 12:29:15 +00:00
Nigel Gott bbd8e58629 🧠 FInal Formula MR 2022-06-28 16:29:56 +00:00
Bram Wiepjes ea66d4197a Added the backend implementation of the premium license per group 2022-06-27 17:56:19 +00:00
Petr Stribny 65c5754985 Implement batch row update api 2022-04-19 10:50:08 +00:00
Bram Wiepjes 7b5e530594 Resolve "Fix premium tests and linter" 2021-11-25 15:30:51 +00:00
Bram Wiepjes cac27f1628 Final branch licensing system 2 2021-10-20 19:28:51 +00:00
Nigel Gott ee7314b64d Resolve "Make it easier to run production version on local machine" 2021-04-22 11:51:15 +00:00
Bram Wiepjes d61db61061 Resolve "Minor changes related to the SaaS version" 2020-04-30 15:07:20 +00:00
Bram Wiepjes 97441b7c09 started django backend project 2019-06-20 19:46:40 +02:00