zylon-ai/private-gpt · error · ValueError
Query not found: {sql_query}
Error message
Query not found: {sql_query} What it means
Raised by the execute_sql_query helper that _process_sql_queries injects into the sandbox: every SQL query found in the generated code is pre-executed and its result written to a CSV keyed by the query string in _datasets_map. At runtime the generated code calls execute_sql_query(sql) and a lookup miss (exact string mismatch) raises this ValueError inside the sandbox. It almost always means the query string used at runtime differs from the one extracted at pre-processing time.
Source
Thrown at private_gpt/components/tabular/pandasai_sandbox.py:343
except Exception as e:
custom_exception = e.__class__(clean_exception_text(str(e)))
exceptions.append(custom_exception)
logger.error("Failed to execute SQL query: %s", custom_exception)
if not datasets_map and exceptions:
return "", exceptions
datasets_code = textwrap.dedent(
f"""
import os
import pandas as pd
_datasets_map = {datasets_map!r}
_temp_dir = {temp_dir!r}
def execute_sql_query(sql_query):
filename = _datasets_map.get(sql_query)
if filename:
return pd.read_csv(os.path.join(_temp_dir, filename))
raise ValueError(f'Query not found: {{sql_query}}')
"""
).strip()
return datasets_code, []
def _prepare_code_for_execution(self, code: str) -> str:
temp_dir = f"/tmp/{self._user_id}"
# Redirect any hardcoded .png paths into the sandbox temp dir
code = re.sub(
r"""(['"])([^'"]*\.png)\1""",
lambda m: (
f"{m.group(1)}{temp_dir}/{os.path.basename(m.group(2))}{m.group(1)}"
),
code,
)
# Replace explicit color lists with CUSTOM_COLORSView on GitHub (pinned to 4a030776a3)
Solutions
- Log both the map keys (_datasets_map) and the failing lookup string to see the exact mismatch.
- Normalize map keys and lookups (strip/collapse whitespace) before comparison.
- Prefer literal SQL strings in generated code — prompt the model not to construct SQL dynamically.
- As a mitigation, fall back to executing the query directly when the lookup misses instead of raising.
Example fix
# before
datasets_code = textwrap.dedent(
f"""
def execute_sql_query(sql_query):
filename = _datasets_map.get(sql_query)
if filename:
return pd.read_csv(os.path.join(_temp_dir, filename))
raise ValueError(f'Query not found: {{sql_query}}')
"""
)
# after (normalized lookup)
_datasets_map_norm = {{k.strip(): v for k, v in _datasets_map.items()}}
def execute_sql_query(sql_query):
filename = _datasets_map_norm.get(sql_query.strip())
if filename:
return pd.read_csv(os.path.join(_temp_dir, filename))
raise ValueError(f'Query not found: {sql_query}') Defensive patterns
Strategy: validation
Validate before calling
# validate before execution: every SQL literal in generated code must be extractable
import re
SQL_RE = re.compile(r'(['"])(SELECT .*?FROM .*?)\1', re.IGNORECASE | re.DOTALL)
def sql_literals_are_static(code: str) -> bool:
return not re.search(r'execute_sql_query\s*\(\s*f?["\'].*\+', code) Prevention
- Prompt the model to pass SQL as exact string literals, never built dynamically
- Normalize whitespace on both map keys and lookups
- Log _datasets_map keys next to the failing lookup for fast diagnosis
When it happens
Trigger: The generated code builds the SQL string dynamically (f-string/concatenation) so the runtime string differs from the literal seen by _extract_sql_queries_from_code; string escaping differences between extraction and execution; whitespace/quoting differences between the extracted query and the map key.
Common situations: LLM writes parameterized or templated SQL; the extraction regex captures a slightly different span than what the code later passes; duplicate near-identical queries with subtle whitespace differences.
Related errors
- Failed to execute some SQL queries: {', '.join(str(e) for e
- Invalid CALL statement format
- Code execution failed: {message}
- Path '{canonical_path}' does not match any session mount.
- Failed to parse JSON: {e!s}
AI-assisted analysis of zylon-ai/private-gpt@4a030776a3 (2026-08-15).
Data as JSON: /api/errors/7cc860f6550e4cb8.
Report an issue: GitHub.