Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(wren-ai-service): improve text2sql transparency #994

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def _additional_meta() -> Dict[str, Any]:
"id": str(uuid.uuid4()),
"meta": {
"type": "TABLE_DESCRIPTION",
"name": chunk["name"],
**_additional_meta(),
},
"content": str(chunk),
Expand Down
61 changes: 46 additions & 15 deletions wren-ai-service/src/pipelines/retrieval/retrieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,20 +224,36 @@ def check_using_db_schemas_without_pruning(
for table_schema in construct_db_schemas:
if table_schema["type"] == "TABLE":
retrieval_results.append(
build_table_ddl(
table_schema,
)
{
"table_name": table_schema["name"],
"table_ddl": build_table_ddl(
table_schema,
),
}
)

for document in dbschema_retrieval:
content = ast.literal_eval(document.content)

if content["type"] == "METRIC":
retrieval_results.append(_build_metric_ddl(content))
retrieval_results.append(
{
"table_name": content["name"],
"table_ddl": _build_metric_ddl(content),
}
)
elif content["type"] == "VIEW":
retrieval_results.append(_build_view_ddl(content))
retrieval_results.append(
{
"table_name": content["name"],
"table_ddl": _build_view_ddl(content),
}
)

_token_count = len(encoding.encode(" ".join(retrieval_results)))
table_ddls = [
retrieval_result["table_ddl"] for retrieval_result in retrieval_results
]
_token_count = len(encoding.encode(" ".join(table_ddls)))
if _token_count > 100_000 or not allow_using_db_schemas_without_pruning:
return {
"db_schemas": [],
Expand Down Expand Up @@ -296,7 +312,7 @@ def construct_retrieval_results(
filter_columns_in_tables: dict,
construct_db_schemas: list[dict],
dbschema_retrieval: list[Document],
) -> list[str]:
) -> list[dict]:
if filter_columns_in_tables:
columns_and_tables_needed = orjson.loads(
filter_columns_in_tables["replies"][0]
Expand All @@ -314,23 +330,38 @@ def construct_retrieval_results(
for table_schema in construct_db_schemas:
if table_schema["type"] == "TABLE" and table_schema["name"] in tables:
retrieval_results.append(
build_table_ddl(
table_schema,
columns=set(
columns_and_tables_needed[table_schema["name"]]["columns"]
{
"table_name": table_schema["name"],
"table_ddl": build_table_ddl(
table_schema,
columns=set(
columns_and_tables_needed[table_schema["name"]][
"columns"
]
),
tables=tables,
),
tables=tables,
)
}
)

for document in dbschema_retrieval:
if document.meta["name"] in columns_and_tables_needed:
content = ast.literal_eval(document.content)

if content["type"] == "METRIC":
retrieval_results.append(_build_metric_ddl(content))
retrieval_results.append(
{
"table_name": content["name"],
"table_ddl": _build_metric_ddl(content),
}
)
elif content["type"] == "VIEW":
retrieval_results.append(_build_view_ddl(content))
retrieval_results.append(
{
"table_name": content["name"],
"table_ddl": _build_view_ddl(content),
}
)
else:
retrieval_results = check_using_db_schemas_without_pruning["db_schemas"]

Expand Down
8 changes: 7 additions & 1 deletion wren-ai-service/src/web/v1/services/ask.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ class AskResultResponse(BaseModel):
rephrased_question: Optional[str] = None
intent_reasoning: Optional[str] = None
type: Optional[Literal["MISLEADING_QUERY", "GENERAL", "TEXT_TO_SQL"]] = None
retrieval_response: Optional[List[str]] = None
response: Optional[List[AskResult]] = None
error: Optional[AskError] = None

Expand Down Expand Up @@ -243,6 +244,8 @@ async def ask(
id=ask_request.project_id,
)
documents = retrieval_result.get("construct_retrieval_results", [])
table_names = [document.get("table_name") for document in documents]
table_ddls = [document.get("table_ddl") for document in documents]

if not documents:
logger.exception(f"ask pipeline - NO_RELEVANT_DATA: {user_query}")
Expand All @@ -267,6 +270,7 @@ async def ask(
type="TEXT_TO_SQL",
rephrased_question=rephrased_question,
intent_reasoning=intent_reasoning,
retrieval_response=table_names,
)

sql_samples = (
Expand Down Expand Up @@ -322,7 +326,7 @@ async def ask(
sql_correction_results = await self._pipelines[
"sql_correction"
].run(
contexts=documents,
contexts=table_ddls,
invalid_generation_results=failed_dry_run_results,
project_id=ask_request.project_id,
)
Expand All @@ -348,6 +352,7 @@ async def ask(
response=api_results,
rephrased_question=rephrased_question,
intent_reasoning=intent_reasoning,
retrieval_response=table_names,
)
results["ask_result"] = api_results
results["metadata"]["type"] = "TEXT_TO_SQL"
Expand All @@ -363,6 +368,7 @@ async def ask(
),
rephrased_question=rephrased_question,
intent_reasoning=intent_reasoning,
retrieval_response=table_names,
)
results["metadata"]["error_type"] = "NO_RELEVANT_SQL"
results["metadata"]["type"] = "TEXT_TO_SQL"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ async def _validate_question(
id=project_id,
)
documents = retrieval_result.get("construct_retrieval_results", [])
table_ddls = [document.get("table_ddl") for document in documents]
generated_sql = await self._pipelines["sql_generation"].run(
query=candidate["question"],
contexts=documents,
contexts=table_ddls,
exclude=[],
configuration=Configuration(),
project_id=project_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_single_table_description():
assert len(actual["documents"]) == 1

document: Document = actual["documents"][0]
assert document.meta == {"type": "TABLE_DESCRIPTION"}
assert document.meta == {"type": "TABLE_DESCRIPTION", "name": "user"}
assert document.content == str(
{
"name": "user",
Expand Down Expand Up @@ -71,6 +71,7 @@ def test_multiple_table_descriptions():
document_1: Document = actual["documents"][0]
assert document_1.meta == {
"type": "TABLE_DESCRIPTION",
"name": "user",
}
assert document_1.content == str(
{
Expand All @@ -81,7 +82,7 @@ def test_multiple_table_descriptions():
)

document_2: Document = actual["documents"][1]
assert document_2.meta == {"type": "TABLE_DESCRIPTION"}
assert document_2.meta == {"type": "TABLE_DESCRIPTION", "name": "order"}
assert document_2.content == str(
{
"name": "order",
Expand Down Expand Up @@ -121,7 +122,7 @@ def test_table_description_missing_description():
assert len(actual["documents"]) == 1

document: Document = actual["documents"][0]
assert document.meta == {"type": "TABLE_DESCRIPTION"}
assert document.meta == {"type": "TABLE_DESCRIPTION", "name": "user"}
assert document.content == str(
{"name": "user", "mdl_type": "MODEL", "description": ""}
)
Expand Down
Loading