querygate-spark 0.4.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- querygate_spark/__init__.py +13 -0
- querygate_spark/cli.py +173 -0
- querygate_spark/config.py +122 -0
- querygate_spark/core.py +209 -0
- querygate_spark/dotenv.py +140 -0
- querygate_spark/llm.py +104 -0
- querygate_spark/parser.py +31 -0
- querygate_spark/prompts/__init__.py +45 -0
- querygate_spark/prompts/error_interpreter.py +85 -0
- querygate_spark/prompts/model_validator.py +1038 -0
- querygate_spark/redact.py +49 -0
- querygate_spark/result.py +49 -0
- querygate_spark/rules.py +647 -0
- querygate_spark-0.4.3.dist-info/METADATA +210 -0
- querygate_spark-0.4.3.dist-info/RECORD +18 -0
- querygate_spark-0.4.3.dist-info/WHEEL +4 -0
- querygate_spark-0.4.3.dist-info/entry_points.txt +2 -0
- querygate_spark-0.4.3.dist-info/licenses/LICENSE +200 -0
querygate_spark/llm.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""LLM calls through LiteLLM, plus robust JSON extraction from model output."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from .config import Settings, _gemini_key_alias
|
|
10
|
+
|
|
11
|
+
_FENCED = re.compile(r"`{3}(?:json)?\s*(\{.*?\})\s*`{3}", re.S)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def extract_json(text: Optional[str]) -> Optional[dict]:
|
|
15
|
+
"""Parse a JSON object from model output (see extract_json_info)."""
|
|
16
|
+
return extract_json_info(text)[0]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def extract_json_info(text: Optional[str]):
|
|
20
|
+
"""Parse a JSON object from model output: plain JSON, a ```json fenced block,
|
|
21
|
+
or the first balanced {...} object embedded in prose. None if nothing parses."""
|
|
22
|
+
"""Return (obj, how): how is "json", "fenced" or "embedded", or (None, None)."""
|
|
23
|
+
if not text:
|
|
24
|
+
return None, None
|
|
25
|
+
s = text.strip()
|
|
26
|
+
try:
|
|
27
|
+
obj = json.loads(s)
|
|
28
|
+
return (obj, "json") if isinstance(obj, dict) else (None, None)
|
|
29
|
+
except ValueError:
|
|
30
|
+
pass
|
|
31
|
+
m = _FENCED.search(s)
|
|
32
|
+
if m:
|
|
33
|
+
try:
|
|
34
|
+
obj = json.loads(m.group(1))
|
|
35
|
+
if isinstance(obj, dict):
|
|
36
|
+
return obj, "fenced"
|
|
37
|
+
except ValueError:
|
|
38
|
+
pass
|
|
39
|
+
# first balanced {...} (string-aware)
|
|
40
|
+
start = s.find("{")
|
|
41
|
+
while start != -1:
|
|
42
|
+
depth, in_str, esc = 0, False, False
|
|
43
|
+
for i in range(start, len(s)):
|
|
44
|
+
c = s[i]
|
|
45
|
+
if in_str:
|
|
46
|
+
if esc:
|
|
47
|
+
esc = False
|
|
48
|
+
elif c == "\\":
|
|
49
|
+
esc = True
|
|
50
|
+
elif c == '"':
|
|
51
|
+
in_str = False
|
|
52
|
+
elif c == '"':
|
|
53
|
+
in_str = True
|
|
54
|
+
elif c == "{":
|
|
55
|
+
depth += 1
|
|
56
|
+
elif c == "}":
|
|
57
|
+
depth -= 1
|
|
58
|
+
if depth == 0:
|
|
59
|
+
try:
|
|
60
|
+
obj = json.loads(s[start:i + 1])
|
|
61
|
+
if isinstance(obj, dict):
|
|
62
|
+
return obj, "embedded"
|
|
63
|
+
except ValueError:
|
|
64
|
+
pass
|
|
65
|
+
break
|
|
66
|
+
start = s.find("{", start + 1)
|
|
67
|
+
return None, None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def complete(system: str, user: str, s: Settings) -> str:
|
|
71
|
+
"""One chat completion; returns the response text (see complete_ex)."""
|
|
72
|
+
return complete_ex(system, user, s)["text"]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def complete_ex(system: str, user: str, s: Settings) -> dict:
|
|
76
|
+
"""One chat completion: temperature 0 and JSON output where supported.
|
|
77
|
+
Returns {"text", "usage", "response_format"}. Raises on transport/auth errors."""
|
|
78
|
+
import litellm
|
|
79
|
+
kwargs = dict(model=s.model, temperature=0.0, top_p=0.9, timeout=s.timeout, drop_params=True,
|
|
80
|
+
messages=[{"role": "system", "content": system}, {"role": "user", "content": user}])
|
|
81
|
+
if s.model.startswith(("gemini/", "vertex_ai/")):
|
|
82
|
+
kwargs["top_k"] = 1 # matches the benchmarked configuration
|
|
83
|
+
key = s.api_key or (_gemini_key_alias(os.environ) if s.model.startswith("gemini/") else None)
|
|
84
|
+
if key:
|
|
85
|
+
kwargs["api_key"] = key
|
|
86
|
+
if s.api_base:
|
|
87
|
+
kwargs["api_base"] = s.api_base
|
|
88
|
+
rf = "json_object"
|
|
89
|
+
try:
|
|
90
|
+
resp = litellm.completion(response_format={"type": "json_object"}, **kwargs)
|
|
91
|
+
except Exception as e:
|
|
92
|
+
# some providers/models reject response_format entirely: retry as plain text
|
|
93
|
+
if "response_format" in str(e) or "json" in str(e).lower():
|
|
94
|
+
resp = litellm.completion(**kwargs)
|
|
95
|
+
rf = "none (provider rejected response_format)"
|
|
96
|
+
else:
|
|
97
|
+
raise
|
|
98
|
+
usage = None
|
|
99
|
+
u = getattr(resp, "usage", None)
|
|
100
|
+
if u is not None:
|
|
101
|
+
usage = {k: getattr(u, k, None) for k in ("prompt_tokens", "completion_tokens", "total_tokens")}
|
|
102
|
+
if not any(v is not None for v in usage.values()):
|
|
103
|
+
usage = None
|
|
104
|
+
return {"text": resp.choices[0].message.content or "", "usage": usage, "response_format": rf}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import sqlglot
|
|
2
|
+
from sqlglot.errors import ParseError
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def validate_sql_syntax(sql: str) -> dict:
|
|
6
|
+
"""
|
|
7
|
+
Validate the syntax of a SQL query using SQLGlot (Spark dialect).
|
|
8
|
+
|
|
9
|
+
Parameters:
|
|
10
|
+
sql (str): The SQL query string to validate.
|
|
11
|
+
|
|
12
|
+
Returns:
|
|
13
|
+
dict: {
|
|
14
|
+
"valid": True | False | None,
|
|
15
|
+
"message": str,
|
|
16
|
+
}
|
|
17
|
+
valid is True when SQLGlot parses the query, False when SQLGlot raises a
|
|
18
|
+
ParseError, and None when SQLGlot crashes with any other exception
|
|
19
|
+
(e.g. IndexError on MAP with an odd argument count). None means the
|
|
20
|
+
parser could not decide; callers should fall back to the model validator.
|
|
21
|
+
"""
|
|
22
|
+
try:
|
|
23
|
+
sqlglot.parse_one(sql, read="spark")
|
|
24
|
+
return {"valid": True, "message": "SQL syntax is valid."}
|
|
25
|
+
except ParseError as e:
|
|
26
|
+
return {"valid": False, "message": f"Syntax error: {e}"}
|
|
27
|
+
except Exception as e: # SQLGlot internal crash: undecided, not a verdict
|
|
28
|
+
return {
|
|
29
|
+
"valid": None,
|
|
30
|
+
"message": f"Parser could not decide ({type(e).__name__}: {e})",
|
|
31
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""The two QueryGate prompts, byte-identical to the benchmarked ADK version,
|
|
2
|
+
plus an ADK-compatible renderer for their `{name}` placeholders."""
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .error_interpreter import ERROR_INTERPRETER_PROMPT
|
|
6
|
+
from .model_validator import MODEL_VALIDATOR_PROMPT
|
|
7
|
+
|
|
8
|
+
__all__ = ["MODEL_VALIDATOR_PROMPT", "ERROR_INTERPRETER_PROMPT", "render",
|
|
9
|
+
"MODEL_VALIDATOR_DESCRIPTION", "ERROR_INTERPRETER_DESCRIPTION", "identity"]
|
|
10
|
+
|
|
11
|
+
# Agent descriptions used by the benchmarked ADK agents (ADK prepends an
|
|
12
|
+
# identity line built from name + description to the system instruction).
|
|
13
|
+
MODEL_VALIDATOR_NAME = "ModelBasedValidatorAgent"
|
|
14
|
+
MODEL_VALIDATOR_DESCRIPTION = ("Strict Spark SQL validator. Returns only structured JSON output. "
|
|
15
|
+
"Does not explain, repair, or interpret user queries.")
|
|
16
|
+
ERROR_INTERPRETER_NAME = "ErrorInterpreterAgent"
|
|
17
|
+
ERROR_INTERPRETER_DESCRIPTION = ("Strict error interpreter for SQL syntax errors. Analyzes provided SQL query and "
|
|
18
|
+
"error message, returning only structured JSON output with clear syntax error "
|
|
19
|
+
"explanation.")
|
|
20
|
+
|
|
21
|
+
# Same pattern and semantics as google.adk's state injection: a {...} group is
|
|
22
|
+
# replaced only when its content is a valid identifier present in `state`;
|
|
23
|
+
# anything else (e.g. JSON examples) is left untouched.
|
|
24
|
+
_TEMPLATE_VAR = re.compile(r"(?<![\$\{\\]){+[^{}]*}+")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def render(template: str, state: dict) -> str:
|
|
28
|
+
def repl(m):
|
|
29
|
+
name = m.group().lstrip("{").rstrip("}").strip()
|
|
30
|
+
optional = name.endswith("?")
|
|
31
|
+
name = name.removesuffix("?")
|
|
32
|
+
if not name.isidentifier():
|
|
33
|
+
return m.group()
|
|
34
|
+
if name in state:
|
|
35
|
+
v = state[name]
|
|
36
|
+
return "" if v is None else str(v)
|
|
37
|
+
if optional:
|
|
38
|
+
return ""
|
|
39
|
+
raise KeyError(f"Context variable not found: `{name}`")
|
|
40
|
+
return _TEMPLATE_VAR.sub(repl, template)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def identity(name: str, description: str) -> str:
|
|
44
|
+
"""The identity line ADK adds in front of an agent's instruction."""
|
|
45
|
+
return f'You are an agent. Your internal name is "{name}". The description about you is "{description}".'
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
ERROR_INTERPRETER_PROMPT = """
|
|
2
|
+
You are a STRICTLY error interpreter service.
|
|
3
|
+
|
|
4
|
+
Your task is to analyze a provided SQL query and its corresponding raw syntax error message. Based on this information, you will explain the syntax error in simple, clear language.
|
|
5
|
+
|
|
6
|
+
Follow these guidelines exactly:
|
|
7
|
+
1. Read the SQL query from : {sql_to_validate} and syntax error message from : {error}
|
|
8
|
+
2. Based on the {sql_to_validate} SQL query and the {error} message, clearly explain *only* the syntax error.
|
|
9
|
+
3. Your explanation must be in simple language.
|
|
10
|
+
4. Do NOT suggest fixes, tips, or alternative SQL.
|
|
11
|
+
5. Do NOT assume schema or database context. Focus strictly on the syntax error message provided above.
|
|
12
|
+
|
|
13
|
+
**Ignore any previous SQL queries or validation results mentioned in the conversation history. Focus solely on the SQL query and error message provided above for this turn.**
|
|
14
|
+
|
|
15
|
+
Return the result in the following strict JSON format:
|
|
16
|
+
|
|
17
|
+
{
|
|
18
|
+
"isValidSQL": false,
|
|
19
|
+
"summary": "<clear explanation of the syntax error>"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
Return ONLY the raw JSON object. No comments, no markdown, no corrected queries.
|
|
23
|
+
|
|
24
|
+
Examples:
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
Scenario 1: Missing FROM clause
|
|
28
|
+
SQL Query: SELECT id, name users;
|
|
29
|
+
Error Message: "ERROR 1000: Line 1, Col 15: Missing FROM keyword at or near 'users'"
|
|
30
|
+
Response:
|
|
31
|
+
{
|
|
32
|
+
"isValidSQL": false,
|
|
33
|
+
"summary": "The FROM keyword is missing before the table name 'users'."
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
Scenario 2: Invalid column separator
|
|
38
|
+
SQL Query: SELECT name age FROM employees;
|
|
39
|
+
Error Message: "Parse error at line 1, column 11. Expected comma or AS keyword after 'name'."
|
|
40
|
+
Response:
|
|
41
|
+
{
|
|
42
|
+
"isValidSQL": false,
|
|
43
|
+
"summary": "There is a missing comma between the column names 'name' and 'age' in the SELECT clause."
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
Scenario 3: Incomplete JOIN clause
|
|
48
|
+
SQL Query: SELECT a.id FROM tableA a JOIN tableB b;
|
|
49
|
+
Error Message: "Semantic error: JOIN clause requires an ON or USING condition."
|
|
50
|
+
Response:
|
|
51
|
+
{
|
|
52
|
+
"isValidSQL": false,
|
|
53
|
+
"summary": "A JOIN clause must be followed by an ON or USING condition."
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
Scenario 4: Invalid operator
|
|
58
|
+
SQL Query: SELECT value FROM data WHERE value >>> 10;
|
|
59
|
+
Error Message: "Syntax error: Unexpected token '>>>' at line 1, column 25."
|
|
60
|
+
Response:
|
|
61
|
+
{
|
|
62
|
+
"isValidSQL": false,
|
|
63
|
+
"summary": "An invalid operator '>>>' was used in the WHERE clause."
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
Scenario 6: Common SQL error (e.g., from SQL parser) - *Crucial for your scenario!*
|
|
68
|
+
SQL Query: SELECT * FROM unknown_database.my_table;
|
|
69
|
+
Error Message: "Error: Database 'unknown_database' not found in catalog." // This is simulating the error from an external SQL parser, not your LLM's own check
|
|
70
|
+
Response:
|
|
71
|
+
{
|
|
72
|
+
"isValidSQL": false,
|
|
73
|
+
"summary": "The error message indicates that the database 'unknown_database' was not found. This is a schema or catalog issue, not a syntax error."
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
Scenario 7: Another common external error
|
|
78
|
+
SQL Query: INSERT INTO my_table VALUES (1, 'value');
|
|
79
|
+
Error Message: "ERROR: column "name" does not exist at character 30"
|
|
80
|
+
Response:
|
|
81
|
+
{
|
|
82
|
+
"isValidSQL": false,
|
|
83
|
+
"summary": "The error indicates that the column 'name' does not exist in the table. This is a schema-related error."
|
|
84
|
+
}
|
|
85
|
+
"""
|