ai-powered-conversational-intelligence

11 — Analytical Intent Classification

Prompt 11 of the 32-prompt Enterprise AI Analytics & Recommendation Platform initiative (00_MASTER_IMPLEMENTATION_CONTRACT.md), following 10_GOVERNED_METRICS_CONTRACT.md. INSPECT/PLAN/IMPLEMENT/TEST/ REVIEW/FIX/DOCUMENT — one new typed-contract module, a new LangGraph node that runs on every question, a widened (never narrowed) plan_query_node gate, and additive config/eval surface. No existing route, node, or Settings field changed behavior for a caller whose question classification is disabled, unreachable, or unparseable.

1. Inspection: what already existed vs. the real gap

02_TARGET_ARCHITECTURE.md §2 named this exact gap back in Prompt 02: the only “intent”-shaped classification in this codebase was agent.followup.classify_followup (standalone/followup/ambiguous — a conversational classification, the one node allowed to short-circuit the graph to END) and agent.complexity’s four regex trip-wires (top_n_per_group/growth_comparison/ranking_window/multi_metric — a narrow “is this complex enough to widen the retry budget / bother planning” signal, not a classifier). Neither answers “what kind of analytical question is this” in any general sense. recommendation /models.py’s RecommendationKind is a different axis entirely (what kind of suggestion to make, not what kind of question was asked) and was confirmed unrelated.

plan_query_node (gated LLM call, fails open on OllamaUnavailableError only, threads selected_model/retrieved_context, shares the existing retry_count/max_retries/AttemptRecord/error_history machinery) was confirmed as the exact template every new advisory LLM-calling node in this series clones — but critically, agent.complexity.compute_max_retries and state["complexity_signals"] are computed once in run_agent() before build_graph()/.invoke() even run (verified via direct line-anchored inspection), so no graph node — including a new one — can retroactively widen the retry budget itself. This forced the design decision that a new intent classifier must be purely advisory to plan_query_node’s own gate/prompt, never to the retry budget. Permission.ASK is enforced by a FastAPI dependency strictly before run_agent/the graph are even constructed (verified directly in api/main.py), which is the structural proof that any new node deep inside the graph cannot bypass authorization, by construction.

2. What was built

Typed contract — agent/intent.py (new)

Mirrors the established “typed contract module, separate from the LLM-calling module” split (agent/followup.py, agent/provenance.py, semantic/catalog.py):

LLM call + parsing — agent/llm_client.py (extended)

New _INTENT_SYSTEM_PROMPT (the same security-override boilerplate every system prompt in this file repeats; the 13 intent values and 6 result-shape values are interpolated directly from AnalyticalIntentType/ExpectedResultShape, never duplicated as a separate literal list that could drift). New _build_intent_governing_metrics_block renders governing-metric names only (never the full approved expression _build_mandatory_metrics_block renders for generation) — enough grounding to let the model name a real governed metric in metric_candidates when one plainly applies, without conflating it with this call’s own output. New _build_intent_user_prompt — deliberately lean, no full schema DDL (classification is about the question’s own wording, not the schema it will eventually be matched against — keeping this call cheap matters more than schema-grounding it, since it runs on every question). New _parse_intent_response(raw_response) -> dict | None — reuses the existing _JSON_FENCE_RE constant (not duplicated), json.loadss, then AnalyticalIntentClassification .model_validate(...) inside a try/except (ValidationError, json.JSONDecodeError, ValueError) → None on any failure, returning .model_dump(mode="json") on success. New generate_analytical_intent_from_llm(question, settings, model=None, retrieved_context=None, governing_metrics=None) -> dict | None — clones generate_query_plan_from_llm’s exact call shape (temperature=0.0, the new Settings.intent_classification_max_tokens, the same OllamaUnavailableError re-raise, the same _log_ollama_timing).

New _build_plan_intent_block threads the classification into plan_query_node’s own prompt (mirrors _build_plan_business_concept_ block’s exact shape: DATA framing, None when absent), framed as an AI_INFERENCE, never confirmed, never an instruction. generate_query_plan_from_llm gained an analytical_intent parameter threading this through — deliberately scoped to planning only, never injected into generate_sql_from_llm’s own prompt directly (it reaches generation only indirectly, through whatever plan it causes to be written), matching the acceptance criterion’s literal wording (“intent influences planning”).

Node + graph wiring

New classify_analytical_intent_node (agent/nodes.py), wired retrieve_business_context → classify_analytical_intent → plan_query (straight edges only, see §3’s “never short-circuits” proof below). Gated only by Settings.enable_intent_classification (default True) — runs on every question when enabled, unlike plan_query_node’s own complexity-gated call, since intent classification is meant to be foundational (per the prompt’s own “before SQL generation” framing). Fails open exactly like plan_query_node: a disabled flag, an unreachable Ollama server, or an unparseable response all resolve to state["analytical_intent"] = None, logged but never a reason the question can’t be answered, and never a terminal status.

The one real behavioral change, and the acceptance-criterion mechanism: plan_query_node’s gate became enable_query_planning and (complexity_signals or intent_triggers_planning), where intent_triggers_planning = analytical_intent is not None and intent_implies_planning(analytical_intent) — reading agent.intent._INTENT_TYPES_IMPLYING_PLANNING indirectly through that helper, never re-deriving its own copy. When analytical_intent is None for any reason, this reduces to exactly complexity_signals alone — byte-identical to this node’s pre-Prompt-11 behavior, preserved by construction, not convention (directly verified by test_none_analytical_intent_reduces_to_pre_prompt_11_behavior and test_lookup_intent_with_no_signals_or_ambiguity_still_skips_planning).

Config

Settings.enable_intent_classification: bool = True, Settings.intent_classification_max_tokens: int = Field(default=250, gt=0) — same on-by-default-but-escapable posture and naming convention as enable_query_planning/query_plan_max_tokens.

Eval harness (diagnostic only, never gates overall_pass)

eval/schema.py’s BenchmarkCase gained optional expected_intent: str | None / expect_ambiguity: bool = False; CaseRunResult gained observed_intent/observed_ambiguity_flags (populated by eval/runner.py from the real state["analytical_intent"]) and a new verdict field intent_classification_correct: bool | None. New eval/evaluators.py::evaluate_intent_classification mirrors evaluate_sql_exact_match’s “None if not applicable, diagnostic only, never referenced by compute_overall_pass” shape exactly — a wrong intent classification never fails an otherwise-correct result (verified by test_intent_classification_correct_never_gates_overall_pass). New eval/metrics.py metric intent_classification_accuracy (same None- means-“not measured” contract as every other category-scoped metric). eval/dataset_loader.py::_parse_case was extended to actually map the two new YAML fields through — a real risk this loader’s own explicit- field-mapping style creates for any new BenchmarkCase field, closed here and covered by a dedicated regression test (test_expected_intent_and_expect_ambiguity_are_parsed).

Six already-live-verified cases across eval/benchmark/easy.yaml/ real_world.yaml were tagged with expected_intent/expect_ambiguity (pure metadata additions, zero new SQL, so no new live-DB verification was needed): easy_filter_red_products (LOOKUP), easy_agg_count_products (AGGREGATION), rw_top5_customers_by_spend (RANKING), rw_gender_breakdown (DISTRIBUTION), and the two already- documented genuinely-ambiguous cases ambig_bikes_top_territory/ ambig_best_selling_product (RANKING + expect_ambiguity: true).

3. Proof: this cannot bypass authorization or short-circuit the graph

4. Explicitly out of scope

5. Testing

6 test files touched (2 new, 4 extended), ~102 new tests, plus 2 pre-existing tests fixed for the new node’s wiring/signature:

Full suite: 2877 tests pass, zero regressions (pytest -q, re-run after every change in this prompt). ruff check/black --check/mypy clean on every new/touched file.

6. Security / tenant-isolation / performance review

7. Known limitations / remaining risks

Per 02_TARGET_ARCHITECTURE.md §5’s own table: wire analytics/ (ResultSummaryAnalyticsProvider) into generate_insight_node and surface AnalyticsResult in AskResponse — unchanged recommendation carried forward from Prompts 04-10, still pending explicit sign-off since it changes a live response shape. Alternatively, a live-LLM run of scripts/run_benchmark.py against the six newly-tagged golden-intent cases to empirically confirm this prompt’s classification accuracy end-to-end (not just the deterministic unit-level proof already in place), or revisiting the DB role/schema configuration in this development environment so a future prompt can live-verify new TREND/COMPARISON benchmark SQL against the real base tables.