Open
feat(nl2sql): 让 Reflector 改完 SQL 后再补维表 JOIN #15
jaxAdd on Sep 18
feat(nl2sql): 让 Reflector 改完 SQL 后再补维表 JOIN #15
Open
Merged fromfeat/reflector-dimension-join-0930intoupstream-br_release_930
Total: 6 files changed+214-23
| @@ -72,14 +72,20 @@ class BaseNL2SQLNode(BaseNode): | |||
| 72 | else: | 72 | else: |
| 73 | self._nl2sql_context_dump_dir = None | 73 | self._nl2sql_context_dump_dir = None |
| 74 | 74 | ||
| 75 | - async def execute_with_llm(self, context: dict[str, str], action: str = "") -> str: | 75 | + async def execute_with_llm( |
| 76 | - """Render the node prompts and asynchronously invoke the configured LLM.""" | 76 | + self, context: dict[str, str], action: str = "", *, prompt_node: str | None = None |
| 77 | + ) -> str: | ||
| 78 | + """Render NL2SQL prompts and asynchronously invoke the configured LLM. | ||
| 79 | + | ||
| 80 | + ``prompt_node`` selects which prompt directory to load. It defaults to | ||
| 81 | + this node's name so callers can reuse another node's templates without | ||
| 82 | + copying the invocation logic. | ||
| 83 | + """ | ||
| 84 | + node = prompt_node or self.name | ||
| 77 | llm = llm_manager.get_default_llm() | 85 | llm = llm_manager.get_default_llm() |
| 78 | - system_prompt = PromptTemplate.from_package_relative( | 86 | + system_prompt = PromptTemplate.from_package_relative(f"{NL2SQL_PROMPT_PREFIX}/{node}/{action}system").content |
| 79 | - f"{NL2SQL_PROMPT_PREFIX}/{self.name}/{action}system" | ||
| 80 | - ).content | ||
| 81 | user_prompt = PromptTemplate.from_package_relative( | 87 | user_prompt = PromptTemplate.from_package_relative( |
| 82 | - f"{NL2SQL_PROMPT_PREFIX}/{self.name}/{action}user" | 88 | + f"{NL2SQL_PROMPT_PREFIX}/{node}/{action}user" |
| 83 | ).apply_prompt_template(**context) | 89 | ).apply_prompt_template(**context) |
| 84 | prompts = [ | 90 | prompts = [ |
| 85 | {"role": "system", "content": system_prompt}, | 91 | {"role": "system", "content": system_prompt}, |
| @@ -87,9 +93,13 @@ class BaseNL2SQLNode(BaseNode): | |||
| 87 | ] | 93 | ] |
| 88 | response = await llm.ainvoke(prompts) | 94 | response = await llm.ainvoke(prompts) |
| 89 | content = response.content | 95 | content = response.content |
| 90 | - self._dump_llm_context(system_prompt, user_prompt, content, self.name, action) | 96 | + self._dump_llm_context(system_prompt, user_prompt, content, node, action) |
| 91 | return content | 97 | return content |
| 92 | 98 | ||
| 99 | + async def execute_dimension_join_llm(self, context: dict[str, str], action: str = "dimension_join_") -> str: | ||
| 100 | + """Rewrite dimension joins with the generator templates, regardless of node name.""" | ||
| 101 | + return await self.execute_with_llm(context, action, prompt_node="generator") | ||
| 102 | + | ||
| 93 | async def execute_with_llm_json(self, context: dict[str, str], action: str = "") -> Any: | 103 | async def execute_with_llm_json(self, context: dict[str, str], action: str = "") -> Any: |
| 94 | """Execute the LLM with the given context and action, returning parsed JSON output.""" | 104 | """Execute the LLM with the given context and action, returning parsed JSON output.""" |
| 95 | for attempt in range(3): | 105 | for attempt in range(3): |
| @@ -116,7 +116,7 @@ class GeneratorNode(BaseNL2SQLNode): | |||
| 116 | state, | 116 | state, |
| 117 | scenario=self._get_agent_config("DATABASE.perceptor_type", ""), | 117 | scenario=self._get_agent_config("DATABASE.perceptor_type", ""), |
| 118 | dialect=self.dialect, | 118 | dialect=self.dialect, |
| 119 | - execute_with_llm=self.execute_with_llm, | 119 | + execute_with_llm=self.execute_dimension_join_llm, |
| 120 | ) | 120 | ) |
| 121 | ) | 121 | ) |
| 122 | state["sql"] = state["generation_results"][0].sql | 122 | state["sql"] = state["generation_results"][0].sql |
| @@ -15,7 +15,7 @@ from typing import Any | |||
| 15 | 15 | ||
| 16 | from dataagent.agents.nl2sql.errors import SQLSecurityValidationError | 16 | from dataagent.agents.nl2sql.errors import SQLSecurityValidationError |
| 17 | from dataagent.agents.nl2sql.nodes.base_nl2sql_node import BaseNL2SQLNode | 17 | from dataagent.agents.nl2sql.nodes.base_nl2sql_node import BaseNL2SQLNode |
| 18 | -from dataagent.agents.nl2sql.utils.nl2sql_utils import quote_sql_placeholders | 18 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import process_dimension_joins, quote_sql_placeholders |
| 19 | from dataagent.agents.nl2sql.workflow.state import NL2SQLState, Result | 19 | from dataagent.agents.nl2sql.workflow.state import NL2SQLState, Result |
| 20 | from dataagent.utils.constants import DEFAULT_NL2SQL_REFLECTOR_THRESHOLD | 20 | from dataagent.utils.constants import DEFAULT_NL2SQL_REFLECTOR_THRESHOLD |
| 21 | from dataagent.utils.log import logger | 21 | from dataagent.utils.log import logger |
| @@ -58,12 +58,26 @@ class ReflectorNode(BaseNL2SQLNode): | |||
| 58 | # skip if fail | 58 | # skip if fail |
| 59 | logger.warning("Reflector failed.") | 59 | logger.warning("Reflector failed.") |
| 60 | fix_sqls = [v.sql for v in state["validation_results"]] | 60 | fix_sqls = [v.sql for v in state["validation_results"]] |
| 61 | + current_batch = [] | ||
| 61 | for v, sql in zip(state["validation_results"], fix_sqls, strict=True): | 62 | for v, sql in zip(state["validation_results"], fix_sqls, strict=True): |
| 62 | v.sql, v.score, v.issues, v.need_ref = sql, 0, [], False | 63 | v.sql, v.score, v.issues, v.need_ref = sql, 0, [], False |
| 63 | v.security_checked = False | 64 | v.security_checked = False |
| 64 | v.security_violations = [] | 65 | v.security_violations = [] |
| 66 | + current_batch.append(v) | ||
| 65 | state["generation_results"].append(v) | 67 | state["generation_results"].append(v) |
| 66 | state["validation_results"].clear() | 68 | state["validation_results"].clear() |
| 69 | + if self._config_manager is not None and current_batch: | ||
| 70 | + rewritten = await process_dimension_joins( | ||
| 71 | + [(item.sql, item.prompt, item.strategy) for item in current_batch], | ||
| 72 | + state, | ||
| 73 | + scenario=self._get_agent_config("DATABASE.perceptor_type", ""), | ||
| 74 | + dialect=self.dialect, | ||
| 75 | + execute_with_llm=self.execute_dimension_join_llm, | ||
| 76 | + ) | ||
| 77 | + for original, new in zip(current_batch, rewritten, strict=True): | ||
| 78 | + original.sql = new.sql | ||
| 79 | + original.prompt = new.prompt | ||
| 80 | + original.need_ref = new.need_ref | ||
| 67 | p = "\n".join([s.sql for s in state["generation_results"]]) | 81 | p = "\n".join([s.sql for s in state["generation_results"]]) |
| 68 | message = f"=== Reflector ===\n{p}" | 82 | message = f"=== Reflector ===\n{p}" |
| 69 | logger.info(message) | 83 | logger.info(message) |
| @@ -325,14 +325,28 @@ async def _process_dimension_candidate( | |||
| 325 | return rewritten, prompt, strategy, dimensions, False | 325 | return rewritten, prompt, strategy, dimensions, False |
| 326 | 326 | ||
| 327 | 327 | ||
| 328 | +def _dimension_rule_line(name: str, mapping: dict[str, str]) -> str: | ||
| 329 | + table = mapping["dimension_table"] | ||
| 330 | + key = mapping["key_column"] | ||
| 331 | + value = mapping["value_column"] | ||
| 332 | + return ( | ||
| 333 | + f"- When `{name}` is projected, use `{table}.{value}` through " | ||
| 334 | + f"`INNER JOIN {table} ON <fact>.{name} = {table}.{key}`. " | ||
| 335 | + "This is a required display-value lookup, not extra business logic; " | ||
| 336 | + "WHERE/HAVING predicates remain on the fact key." | ||
| 337 | + ) | ||
| 338 | + | ||
| 339 | + | ||
| 328 | def _add_dimension_context( | 340 | def _add_dimension_context( |
| 329 | state: NL2SQLState, | 341 | state: NL2SQLState, |
| 330 | dimensions: list[str], | 342 | dimensions: list[str], |
| 331 | mappings: dict[str, dict[str, str]], | 343 | mappings: dict[str, dict[str, str]], |
| 332 | ) -> str: | 344 | ) -> str: |
| 333 | fact_table = next(iter(state["schema"]), "") | 345 | fact_table = next(iter(state["schema"]), "") |
| 334 | - dimension_tables = {} | 346 | + schema_str = state["schema_str"] or "" |
| 335 | - rule_lines = ["## Required Dimension Value Mappings"] | 347 | + sql_rules = state["sql_rules"] or "" |
| 348 | + new_tables: dict[str, dict[str, Any]] = {} | ||
| 349 | + new_rule_lines: list[str] = [] | ||
| 336 | for name in dimensions: | 350 | for name in dimensions: |
| 337 | mapping = mappings[name] | 351 | mapping = mappings[name] |
| 338 | table = mapping["dimension_table"] | 352 | table = mapping["dimension_table"] |
| @@ -344,22 +358,33 @@ def _add_dimension_context( | |||
| 344 | ) | 358 | ) |
| 345 | for column in (key, value): | 359 | for column in (key, value): |
| 346 | table_meta["columns"].setdefault(column, {"description": "", "value_type": ""}) | 360 | table_meta["columns"].setdefault(column, {"description": "", "value_type": ""}) |
| 347 | - dimension_tables[table] = table_meta | ||
| 348 | if fact_table: | 361 | if fact_table: |
| 349 | join = (f"{fact_table}.{name}", f"{table}.{key}") | 362 | join = (f"{fact_table}.{name}", f"{table}.{key}") |
| 350 | if join not in state["joins"]: | 363 | if join not in state["joins"]: |
| 351 | state["joins"].append(join) | 364 | state["joins"].append(join) |
| 352 | - rule_lines.append( | 365 | + if f"CREATE TABLE `{table}`" not in schema_str: |
| 353 | - f"- When `{name}` is projected, use `{table}.{value}` through " | 366 | + new_tables[table] = table_meta |
| 354 | - f"`INNER JOIN {table} ON <fact>.{name} = {table}.{key}`. " | 367 | + rule_line = _dimension_rule_line(name, mapping) |
| 355 | - "This is a required display-value lookup, not extra business logic; " | 368 | + if rule_line not in sql_rules: |
| 356 | - "WHERE/HAVING predicates remain on the fact key." | 369 | + new_rule_lines.append(rule_line) |
| 370 | + parts: list[str] = [] | ||
| 371 | + if new_tables: | ||
| 372 | + schema_ddl = schema_to_ddl(new_tables) | ||
| 373 | + schema_block = ( | ||
| 374 | + schema_ddl if "## Dimension Lookup Schema" in schema_str else f"## Dimension Lookup Schema\n{schema_ddl}" | ||
| 357 | ) | 375 | ) |
| 358 | - schema_context = "## Dimension Lookup Schema\n" + schema_to_ddl(dimension_tables) | 376 | + state["schema_str"] = f"{schema_str}\n\n{schema_block}".strip() |
| 359 | - rules_context = "\n".join(rule_lines) | 377 | + parts.append(schema_block) |
| 360 | - state["schema_str"] = f"{state['schema_str']}\n\n{schema_context}".strip() | 378 | + if new_rule_lines: |
| 361 | - state["sql_rules"] = f"{state['sql_rules']}\n\n{rules_context}".strip() | 379 | + rules_body = "\n".join(new_rule_lines) |
| 362 | - return f"{schema_context}\n\n{rules_context}" | 380 | + rules_block = ( |
| 381 | + rules_body | ||
| 382 | + if "## Required Dimension Value Mappings" in sql_rules | ||
| 383 | + else f"## Required Dimension Value Mappings\n{rules_body}" | ||
| 384 | + ) | ||
| 385 | + state["sql_rules"] = f"{sql_rules}\n\n{rules_block}".strip() | ||
| 386 | + parts.append(rules_block) | ||
| 387 | + return "\n\n".join(parts) | ||
| 363 | 388 | ||
| 364 | 389 | ||
| 365 | async def process_dimension_joins( | 390 | async def process_dimension_joins( |
| @@ -17,7 +17,12 @@ import pytest | |||
| 17 | 17 | ||
| 18 | from dataagent.agents.nl2sql.nodes.generator import GeneratorNode | 18 | from dataagent.agents.nl2sql.nodes.generator import GeneratorNode |
| 19 | from dataagent.agents.nl2sql.security import check_sql | 19 | from dataagent.agents.nl2sql.security import check_sql |
| 20 | -from dataagent.agents.nl2sql.utils.nl2sql_utils import load_dimension_mappings, schema_to_ddl, selected_dimensions | 20 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import ( |
| 21 | + _add_dimension_context, | ||
| 22 | + load_dimension_mappings, | ||
| 23 | + schema_to_ddl, | ||
| 24 | + selected_dimensions, | ||
| 25 | +) | ||
| 21 | from dataagent.agents.nl2sql.workflow.state import get_default_state | 26 | from dataagent.agents.nl2sql.workflow.state import get_default_state |
| 22 | from dataagent.config.config_manager import ConfigManager | 27 | from dataagent.config.config_manager import ConfigManager |
| 23 | from dataagent.core.managers.llm_manager import llm_manager | 28 | from dataagent.core.managers.llm_manager import llm_manager |
| @@ -188,3 +193,19 @@ async def test_keeps_original_and_requests_reflection_when_rewrite_fails(rewrite | |||
| 188 | assert candidate.need_ref is True | 193 | assert candidate.need_ref is True |
| 189 | assert "dim_exp_county" in result["schema"] | 194 | assert "dim_exp_county" in result["schema"] |
| 190 | assert "dim_exp_county" in candidate.prompt | 195 | assert "dim_exp_county" in candidate.prompt |
| 196 | + | ||
| 197 | + | ||
| 198 | +def test_add_dimension_context_appends_only_newly_discovered_dimension() -> None: | ||
| 199 | + state = _state() | ||
| 200 | + mappings = load_dimension_mappings("business_twin") | ||
| 201 | + | ||
| 202 | + _add_dimension_context(state, ["county"], mappings) | ||
| 203 | + added = _add_dimension_context(state, ["county", "city"], mappings) | ||
| 204 | + | ||
| 205 | + assert "dim_exp_city" in added | ||
| 206 | + assert "When `city` is projected" in added | ||
| 207 | + assert "When `county` is projected" not in added | ||
| 208 | + assert state["schema_str"].count("CREATE TABLE `dim_exp_county`") == 1 | ||
| 209 | + assert state["schema_str"].count("CREATE TABLE `dim_exp_city`") == 1 | ||
| 210 | + assert state["sql_rules"].count("When `county` is projected") == 1 | ||
| 211 | + assert state["sql_rules"].count("When `city` is projected") == 1 | ||
| @@ -0,0 +1,121 @@ | |||
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 2 | +# you may not use this file except in compliance with the License. | ||
| 3 | +# You may obtain a copy of the License at | ||
| 4 | +# | ||
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 | ||
| 6 | +# | ||
| 7 | +# Unless required by applicable law or agreed to in writing, software | ||
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, | ||
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 10 | +# See the License for the specific language governing permissions and | ||
| 11 | +# limitations under the License. | ||
| 12 | +# ============================================================================ | ||
| 13 | +from types import SimpleNamespace | ||
| 14 | +from unittest.mock import AsyncMock, patch | ||
| 15 | + | ||
| 16 | +import pytest | ||
| 17 | + | ||
| 18 | +from dataagent.agents.nl2sql.nodes.reflector import ReflectorNode | ||
| 19 | +from dataagent.agents.nl2sql.utils.nl2sql_utils import schema_to_ddl | ||
| 20 | +from dataagent.agents.nl2sql.workflow.state import Result, get_default_state | ||
| 21 | +from dataagent.config.config_manager import ConfigManager | ||
| 22 | +from dataagent.core.managers.llm_manager import llm_manager | ||
| 23 | +from dataagent.core.managers.prompt_manager import PromptTemplate | ||
| 24 | + | ||
| 25 | +BARE_SQL = ( | ||
| 26 | + "SELECT time, county, SUM(uplink_traffic) AS uplink_traffic FROM fact_metric " | ||
| 27 | + "WHERE county = 10 GROUP BY time, county" | ||
| 28 | +) | ||
| 29 | +REWRITTEN_SQL = ( | ||
| 30 | + "SELECT f.time, d.county_value, SUM(f.uplink_traffic) AS uplink_traffic FROM fact_metric f " | ||
| 31 | + "INNER JOIN dim_exp_county d ON f.county = d.county_key " | ||
| 32 | + "WHERE f.county = 10 GROUP BY f.time, d.county_value" | ||
| 33 | +) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def _config_manager(scenario: str = "business_twin") -> ConfigManager: | ||
| 37 | + manager = ConfigManager() | ||
| 38 | + manager.settings = { | ||
| 39 | + "DATABASE": { | ||
| 40 | + "dialect": "postgres", | ||
| 41 | + "perceptor_type": scenario, | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + return manager | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def _node() -> ReflectorNode: | ||
| 48 | + return ReflectorNode(config_manager=_config_manager(), threshold=0.9) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _state() -> dict: | ||
| 52 | + schema = { | ||
| 53 | + "fact_metric": { | ||
| 54 | + "description": "fact", | ||
| 55 | + "columns": { | ||
| 56 | + "time": {"value_type": "bigint"}, | ||
| 57 | + "county": {"value_type": "integer"}, | ||
| 58 | + "uplink_traffic": {"value_type": "numeric"}, | ||
| 59 | + }, | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + state = get_default_state( | ||
| 63 | + "query traffic by county", | ||
| 64 | + schema=schema, | ||
| 65 | + schema_str=schema_to_ddl(schema), | ||
| 66 | + sql_rules="Keep the requested time range.", | ||
| 67 | + ref_retries=1, | ||
| 68 | + ) | ||
| 69 | + state["validation_results"] = [ | ||
| 70 | + Result( | ||
| 71 | + id=0, | ||
| 72 | + sql="SELECT 1", | ||
| 73 | + prompt="original generator prompt", | ||
| 74 | + score=0.1, | ||
| 75 | + need_ref=True, | ||
| 76 | + security_checked=True, | ||
| 77 | + ) | ||
| 78 | + ] | ||
| 79 | + return state | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +@pytest.mark.asyncio | ||
| 83 | +async def test_reflector_dimension_join_loads_generator_prompts_not_reflector() -> None: | ||
| 84 | + node = _node() | ||
| 85 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": BARE_SQL}]) | ||
| 86 | + loaded: list[str] = [] | ||
| 87 | + real_loader = PromptTemplate.from_package_relative | ||
| 88 | + | ||
| 89 | + def tracking_loader(path: str): | ||
| 90 | + loaded.append(path) | ||
| 91 | + return real_loader(path) | ||
| 92 | + | ||
| 93 | + llm = SimpleNamespace(ainvoke=AsyncMock(return_value=SimpleNamespace(content=f"```sql\n{REWRITTEN_SQL}\n```"))) | ||
| 94 | + | ||
| 95 | + with ( | ||
| 96 | + patch.object(PromptTemplate, "from_package_relative", side_effect=tracking_loader), | ||
| 97 | + patch.object(llm_manager, "get_default_llm", return_value=llm), | ||
| 98 | + ): | ||
| 99 | + result = await node._aprocess(_state()) | ||
| 100 | + | ||
| 101 | + assert any("generator/dimension_join_" in path for path in loaded) | ||
| 102 | + assert not any("reflector/dimension_join_" in path for path in loaded) | ||
| 103 | + assert "INNER JOIN dim_exp_county" in result["generation_results"][0].sql | ||
| 104 | + assert llm.ainvoke.await_count == 1 | ||
| 105 | + assert ( | ||
| 106 | + "Keep existing `WHERE` and `HAVING` predicates on the fact key" in llm.ainvoke.await_args.args[0][0]["content"] | ||
| 107 | + ) | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +@pytest.mark.asyncio | ||
| 111 | +async def test_reflector_keeps_reflected_sql_when_dimension_join_fails() -> None: | ||
| 112 | + node = _node() | ||
| 113 | + node.execute_with_llm_json = AsyncMock(return_value=[{"id": 0, "sql": BARE_SQL}]) | ||
| 114 | + llm = SimpleNamespace(ainvoke=AsyncMock(side_effect=RuntimeError("rewrite unavailable"))) | ||
| 115 | + | ||
| 116 | + with patch.object(llm_manager, "get_default_llm", return_value=llm): | ||
| 117 | + result = await node._aprocess(_state()) | ||
| 118 | + | ||
| 119 | + candidate = result["generation_results"][0] | ||
| 120 | + assert candidate.sql == BARE_SQL | ||
| 121 | + assert candidate.need_ref is True | ||