Skip to content

added ambiguity node after schema explorer#26

Open
yuvalkh wants to merge 4 commits into
mainfrom
yuval/detect-ambiguity
Open

added ambiguity node after schema explorer#26
yuvalkh wants to merge 4 commits into
mainfrom
yuval/detect-ambiguity

Conversation

@yuvalkh

@yuvalkh yuvalkh commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added automatic ambiguity detection before SQL generation.
    • Users can clarify ambiguous requests through an interactive resolution flow.
    • Added retry handling and clear “unanswerable” outcomes when requests cannot be resolved.
    • Unanswerable results now appear with a distinct failure status in the testing interface.
  • Bug Fixes

    • Improved satisfaction checks for queries returning only the directly requested fields.
    • Improved error formatting and session handling during agent interactions.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The agent adds a dedicated ambiguity-detection and HITL clarification path before SQL generation, with retry limits and unanswerable outcomes. API and frontend contracts expose this status, while schema exploration and diagnostic failure messages are updated accordingly.

Changes

Ambiguity workflow

Layer / File(s) Summary
Ambiguity contracts and schema exploration
agent/scripts/upload_all_prompts.py, agent/src/agent/config.py, agent/src/agent/state.py, agent/src/agent/nodes/schema_explorer.py, agent/src/agent/utils/schema_enrichment.py
A dedicated ambiguity prompt, state fields, retry settings, and simplified schema-explorer output replace the previous inline ambiguity handling.
Ambiguity detection and clarification nodes
agent/src/agent/nodes/detect_ambiguity.py
Structured LLM classification produces clear, ambiguous, or unanswerable outcomes, while HITL clarification updates the query and retries schema exploration.
Graph routing and resume integration
agent/src/agent/graph.py, agent/src/agent/mcp_server.py
The graph adds ambiguity routing and interruption points; resumed feedback is mapped into state, Langfuse handlers are flushed conditionally, and final responses include unanswerable status.
Unanswerable response presentation
backend/app/routers/agent.py, frontend/src/api/agent.ts, frontend/src/pages/AgentTestingPage.tsx
The response contract carries is_unanswerable, and the testing page renders a failure state for unanswerable results while creating fresh thread IDs.
Diagnostic prompt and failure formatting
agent/src/agent/nodes/satisfaction_check.py, agent/src/agent/nodes/refiner.py
Satisfaction prompts allow exact requested-column results, and failure details use multiline bullet formatting.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant MCPServer
  participant SchemaExplorer
  participant DetectAmbiguity
  participant AmbiguityResolution
  participant QueryBuilder
  User->>MCPServer: Submit request
  MCPServer->>SchemaExplorer: Execute schema exploration
  SchemaExplorer->>DetectAmbiguity: schema_plan and schema context
  DetectAmbiguity->>DetectAmbiguity: Classify ambiguity
  DetectAmbiguity->>QueryBuilder: Clear result
  DetectAmbiguity->>AmbiguityResolution: Ambiguous result and questions
  User->>MCPServer: Provide clarification
  MCPServer->>AmbiguityResolution: Resume with feedback
  AmbiguityResolution->>SchemaExplorer: Retry with updated user_query
  DetectAmbiguity-->>MCPServer: Unanswerable result
  MCPServer-->>User: is_unanswerable response
Loading

Possibly related PRs

Poem

A rabbit found a query unclear,
So asked for a carrot of context dear.
The graph paused, then hopped anew,
With retries counted—one, then two.
Clear SQL sprang from the plan,
Or “unanswerable” told the clan.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding an ambiguity-handling node into the schema explorer flow.
Docstring Coverage ✅ Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch yuval/detect-ambiguity

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/src/agent/nodes/detect_ambiguity.py`:
- Around line 155-165: Update the parse-failure fallback in detect_ambiguity to
use a generic user-facing clarification in the reason field, preventing raw
exception details from reaching downstream clarifying-question output. Keep the
captured exception available only through logging or internal ambiguity_result
data, while preserving the existing ambiguous classification.

In `@agent/src/agent/nodes/schema_explorer.py`:
- Around line 525-529: Update the exception fallback in the schema explorer
parsing flow to construct SchemaExplorerOutput with an empty string (or the
model’s valid default) for schema_plan instead of None. Preserve the existing
plan = data.schema_plan or "" recovery behavior so parsing failures return
normally without triggering another validation error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 26a079bf-e99e-4260-b056-0974e018258d

📥 Commits

Reviewing files that changed from the base of the PR and between 45b5194 and 6fd396d.

📒 Files selected for processing (14)
  • agent/scripts/upload_all_prompts.py
  • agent/src/agent/config.py
  • agent/src/agent/graph.py
  • agent/src/agent/mcp_server.py
  • agent/src/agent/nodes/detect_ambiguity.py
  • agent/src/agent/nodes/refiner.py
  • agent/src/agent/nodes/satisfaction_check.py
  • agent/src/agent/nodes/schema_explorer.py
  • agent/src/agent/state.py
  • agent/src/agent/utils/flag_bridge.py
  • agent/src/agent/utils/schema_enrichment.py
  • backend/app/routers/agent.py
  • frontend/src/api/agent.ts
  • frontend/src/pages/AgentTestingPage.tsx
💤 Files with no reviewable changes (1)
  • agent/src/agent/utils/flag_bridge.py

Comment thread agent/src/agent/nodes/detect_ambiguity.py
Comment thread agent/src/agent/nodes/schema_explorer.py
Comment thread agent/src/agent/utils/flag_bridge.py
Comment thread agent/src/agent/nodes/detect_ambiguity.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
agent/src/agent/nodes/detect_ambiguity.py (1)

263-274: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Pass the fallback clarification via feedback so it reaches schema_explorer.

When the user provides no feedback, the code constructs user_feedback with the previous question but then explicitly omits it from new_query and sets "feedback": None. This discards the fallback context entirely, leaving schema_explorer with the exact same inputs as the previous run. This will result in a loop of identical outputs until max retries are hit.

Pass the fallback context via the feedback state field so schema_explorer can use it. The downstream sql_static_validations_node will safely clear it before it reaches the rejection_router.

🐛 Proposed fix
     new_query = state.get("user_query", "")
     if user_feedback and not user_feedback.startswith("[Previous"):
         new_query += f"\n[User Clarification: {user_feedback}]"
 
     return {
         # Update the main query so all subsequent nodes see the unified intent.
         "user_query": new_query,
         # Clear ambiguity decision so detect_ambiguity re-evaluates cleanly on retry.
         "ambiguity_type": None,
         "ambiguity_result": None,
         "clarifying_questions": None,
-        # Clear feedback so it doesn't accidentally trigger the rejection_router later.
-        "feedback": None,
+        # Pass the previous question as feedback if no user clarification was provided;
+        # sql_static_validations_node will safely clear it later.
+        "feedback": user_feedback if user_feedback.startswith("[Previous") else None,
         "ambiguity_retry_count": retry_count,
         "execution_path": ["ambiguity_resolution"],
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/src/agent/nodes/detect_ambiguity.py` around lines 263 - 274, Update the
retry return state in the ambiguity-handling flow to preserve the constructed
fallback user_feedback through the "feedback" field instead of setting it to
None. Keep the existing new_query behavior for explicit feedback, and ensure
schema_explorer receives the fallback clarification while downstream validation
clears it before rejection routing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/src/agent/nodes/detect_ambiguity.py`:
- Around line 157-166: Update the exception fallback result in the ambiguity
detection flow to include only the current AmbiguityResult fields:
ambiguity_type, reason, and clarifying_questions. Remove intent_deconstruction,
active_schema_search, ambiguity_check, logical_sql_plan, and
schema_alignment_check from the parsed fallback.

---

Outside diff comments:
In `@agent/src/agent/nodes/detect_ambiguity.py`:
- Around line 263-274: Update the retry return state in the ambiguity-handling
flow to preserve the constructed fallback user_feedback through the "feedback"
field instead of setting it to None. Keep the existing new_query behavior for
explicit feedback, and ensure schema_explorer receives the fallback
clarification while downstream validation clears it before rejection routing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 43eabab8-5f21-4f33-8c74-0657b5e4be95

📥 Commits

Reviewing files that changed from the base of the PR and between 6fd396d and 4952fc7.

📒 Files selected for processing (2)
  • agent/src/agent/nodes/detect_ambiguity.py
  • agent/src/agent/nodes/schema_explorer.py

Comment thread agent/src/agent/nodes/detect_ambiguity.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
agent/src/agent/config.py (1)

46-46: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep ambiguity detection disabled until its Langfuse prompt is guaranteed to exist. ENABLE_AMBIGUITY_DETECT defaults to True, so upgrades without text2sql/detect_ambiguity will route into detect_ambiguity and raise at request time. Either leave the default off until rollout is complete or provision/validate the prompt at startup.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/src/agent/config.py` at line 46, Update the ambiguity-detection
configuration around ENABLE_AMBIGUITY_DETECT so it defaults to disabled until
the Langfuse prompt identified by LANGFUSE_PROMPT_DETECT_AMBIGUITY is guaranteed
to exist; alternatively, add startup validation/provisioning that verifies this
prompt before enabling the feature.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/src/agent/config.py`:
- Line 73: Update the MAX_AMBIGUITY_RETRIES configuration field to use
validation with a default of 2 and a minimum value of 0, rejecting negative
environment-configured values while preserving zero as valid. Leave the existing
ambiguity retry handling unchanged.

---

Outside diff comments:
In `@agent/src/agent/config.py`:
- Line 46: Update the ambiguity-detection configuration around
ENABLE_AMBIGUITY_DETECT so it defaults to disabled until the Langfuse prompt
identified by LANGFUSE_PROMPT_DETECT_AMBIGUITY is guaranteed to exist;
alternatively, add startup validation/provisioning that verifies this prompt
before enabling the feature.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9b709a29-07df-45ab-923c-ef166ba17b9c

📥 Commits

Reviewing files that changed from the base of the PR and between 4952fc7 and b880a84.

📒 Files selected for processing (3)
  • agent/src/agent/config.py
  • agent/src/agent/graph.py
  • agent/src/agent/nodes/detect_ambiguity.py
💤 Files with no reviewable changes (1)
  • agent/src/agent/nodes/detect_ambiguity.py

Comment thread agent/src/agent/config.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants