text2sql-engine 0.1.0__py3-none-any.whl → 0.2.0__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.
text2sql/__init__.py CHANGED
@@ -37,7 +37,7 @@ from .types import (
37
37
  TokenUsage,
38
38
  )
39
39
 
40
- __version__ = "0.1.0"
40
+ __version__ = "0.2.0"
41
41
 
42
42
  __all__ = [
43
43
  "Text2SQL",
text2sql/config.py CHANGED
@@ -52,6 +52,9 @@ class StageSettings:
52
52
  timeout_seconds: float = 60.0
53
53
  # Used by linking only. Generation ignores it.
54
54
  max_tables: int = 8
55
+ # Used by generation only. "structured" forces JSON (sql + explanation).
56
+ # "raw" asks for plain SQL text. Linking ignores it.
57
+ output_mode: str = "structured"
55
58
 
56
59
 
57
60
  @dataclass
@@ -149,6 +152,7 @@ def _stage_from_toml(
149
152
  if include_max_tables
150
153
  else defaults.max_tables
151
154
  ),
155
+ output_mode=str(table.get("output_mode", defaults.output_mode)).lower(),
152
156
  )
153
157
 
154
158
 
@@ -226,9 +230,21 @@ def load_settings(
226
230
  default_template="linking.txt",
227
231
  include_max_tables=True,
228
232
  )
233
+
234
+ gen_tbl = toml_data.get("generation", {})
235
+ gen_output_mode = str(gen_tbl.get("output_mode", "structured")).lower()
236
+ if gen_output_mode not in ("structured", "raw"):
237
+ raise ConfigError(
238
+ f"[generation] output_mode must be 'structured' or 'raw', "
239
+ f"got '{gen_output_mode}'."
240
+ )
241
+ # In raw mode, default to the raw template unless the user set one.
242
+ gen_default_template = "generation.txt"
243
+ if gen_output_mode == "raw" and "prompt_template" not in gen_tbl:
244
+ gen_default_template = "generation_raw.txt"
229
245
  generation = _stage_from_toml(
230
- toml_data.get("generation", {}),
231
- default_template="generation.txt",
246
+ gen_tbl,
247
+ default_template=gen_default_template,
232
248
  include_max_tables=False,
233
249
  )
234
250
 
@@ -2,13 +2,22 @@
2
2
 
3
3
  Takes the reduced schema from Stage 1 and produces a SQL string, plus an
4
4
  optional short explanation, in the configured dialect.
5
+
6
+ Two output modes (config: [generation] output_mode):
7
+
8
+ * "structured" (default) — force JSON with "sql" and "explanation" fields.
9
+ Reliable parsing. Best for general chat/instruct models.
10
+ * "raw" — ask for plain SQL text. No explanation. Better for specialized
11
+ text-to-SQL models that are trained to emit SQL only.
5
12
  """
6
13
 
7
14
  from __future__ import annotations
8
15
 
16
+ import re
9
17
  from typing import Any
10
18
 
11
19
  from ..config import Settings
20
+ from ..errors import StructuredOutputError
12
21
  from ..logging_utils import get_logger
13
22
  from ..prompts import PromptTemplates
14
23
  from ..providers.base import LLMProvider
@@ -16,6 +25,18 @@ from ..schema import Schema, schema_to_prompt
16
25
  from ..types import LinkedSchema, LLMResponse, StageMetadata, _Timer
17
26
  from .json_utils import extract_json, with_retry
18
27
 
28
+ # Matches a ```sql ... ``` or ``` ... ``` fenced block.
29
+ _FENCE_RE = re.compile(r"```(?:sql)?\s*(.*?)```", re.DOTALL | re.IGNORECASE)
30
+
31
+
32
+ def _strip_sql(text: str) -> str:
33
+ """Return plain SQL from a raw response. Drops markdown fences if present."""
34
+ stripped = text.strip()
35
+ fence = _FENCE_RE.search(stripped)
36
+ if fence:
37
+ return fence.group(1).strip()
38
+ return stripped
39
+
19
40
  logger = get_logger("pipeline.generation")
20
41
 
21
42
  GENERATION_SCHEMA_NAME = "sql_generation"
@@ -61,6 +82,19 @@ class GenerationStage:
61
82
  reduced_schema = full_schema.subset(linked.tables)
62
83
  reduced_text = schema_to_prompt(reduced_schema) if reduced_schema.tables else "(none)"
63
84
 
85
+ # Forward Stage 1's reasoning to Stage 2. The linking model already
86
+ # worked out the logic (ranges, joins, which column means what); the SQL
87
+ # model should follow it instead of guessing.
88
+ columns_text = "\n".join(
89
+ f"- {c.table}.{c.column}" + (f" — {c.reason}" if c.reason else "")
90
+ for c in linked.columns
91
+ ) or "(none)"
92
+ joins_text = "\n".join(
93
+ f"- {j.left_table}.{j.left_column} = {j.right_table}.{j.right_column}"
94
+ for j in linked.joins
95
+ ) or "(none)"
96
+ rationale_text = linked.rationale.strip() or "(none)"
97
+
64
98
  template = self._prompts.load(stage_cfg.prompt_template)
65
99
  system, user = template.render(
66
100
  linked_schema=reduced_text,
@@ -68,11 +102,14 @@ class GenerationStage:
68
102
  dialect=self._settings.general.sql_dialect,
69
103
  entities=", ".join(linked.entities) or "(none)",
70
104
  filters="; ".join(linked.filters) or "(none)",
105
+ columns=columns_text,
106
+ joins=joins_text,
107
+ rationale=rationale_text,
71
108
  )
72
109
 
73
110
  attempts = {"n": 0}
74
111
 
75
- def attempt() -> tuple[str, str, LLMResponse]:
112
+ def attempt_structured() -> tuple[str, str, LLMResponse]:
76
113
  attempts["n"] += 1
77
114
  response = self._provider.complete_json(
78
115
  system=system,
@@ -87,11 +124,26 @@ class GenerationStage:
87
124
  sql = str(data.get("sql", "")).strip()
88
125
  explanation = str(data.get("explanation", "")).strip()
89
126
  if not sql:
90
- from ..errors import StructuredOutputError
91
-
92
127
  raise StructuredOutputError("Generation returned an empty 'sql' field.")
93
128
  return sql, explanation, response
94
129
 
130
+ def attempt_raw() -> tuple[str, str, LLMResponse]:
131
+ attempts["n"] += 1
132
+ response = self._provider.complete(
133
+ system=system,
134
+ user=user,
135
+ temperature=stage_cfg.temperature,
136
+ top_p=stage_cfg.top_p,
137
+ max_tokens=stage_cfg.max_tokens,
138
+ )
139
+ sql = _strip_sql(response.text)
140
+ if not sql:
141
+ raise StructuredOutputError("Generation returned empty SQL.")
142
+ # Raw mode does not produce an explanation.
143
+ return sql, "", response
144
+
145
+ attempt = attempt_raw if stage_cfg.output_mode == "raw" else attempt_structured
146
+
95
147
  with _Timer() as timer:
96
148
  sql, explanation, response = with_retry(
97
149
  attempt,
@@ -1,12 +1,17 @@
1
1
  SYSTEM:
2
- You are an expert SQL generator. You get a user request and a reduced schema
3
- (only the relevant tables/columns/joins picked by an upstream linking step).
4
- Produce one correct SQL query in the target dialect.
2
+ You are an expert SQL generator. You get a user request, a reduced schema (only
3
+ the relevant tables/columns/joins picked by an upstream linking step), and that
4
+ step's analysis. Produce one correct SQL query in the target dialect.
5
5
 
6
6
  Rules:
7
7
  - Use only the tables and columns in the reduced schema.
8
+ - Follow the linking analysis. It already worked out the logic; do not ignore it.
9
+ - Respect the intended comparison semantics from the analysis and filter hints.
10
+ If a value should be matched by a numeric range or an exact compare, implement
11
+ it that way. Do not fall back to substring/text (LIKE) matching unless that is
12
+ clearly what is meant.
13
+ - Use the suggested joins to connect tables. Prefer explicit JOINs.
8
14
  - Write idiomatic SQL for the target dialect: {dialect}.
9
- - Prefer explicit JOINs using the given relations.
10
15
  - Do not run the query. Only produce it.
11
16
  - Return the answer strictly as the requested JSON object with two fields:
12
17
  "sql" (the query) and "explanation" (one or two sentences).
@@ -19,6 +24,15 @@ Reduced schema (relevant subset):
19
24
  {linked_schema}
20
25
  --------------------------------
21
26
 
27
+ Linking analysis (reasoning from the previous step — follow this logic):
28
+ {rationale}
29
+
30
+ Relevant columns:
31
+ {columns}
32
+
33
+ Suggested joins:
34
+ {joins}
35
+
22
36
  Detected entities: {entities}
23
37
  Filter hints: {filters}
24
38
 
@@ -0,0 +1,41 @@
1
+ SYSTEM:
2
+ You are an expert SQL generator. You get a user request, a reduced schema (only
3
+ the relevant tables/columns/joins picked by an upstream linking step), and that
4
+ step's analysis. Produce one correct SQL query in the target dialect.
5
+
6
+ Rules:
7
+ - Use only the tables and columns in the reduced schema.
8
+ - Follow the linking analysis. It already worked out the logic; do not ignore it.
9
+ - Respect the intended comparison semantics from the analysis and filter hints.
10
+ If a value should be matched by a numeric range or an exact compare, implement
11
+ it that way. Do not fall back to substring/text (LIKE) matching unless that is
12
+ clearly what is meant.
13
+ - Use the suggested joins to connect tables. Prefer explicit JOINs.
14
+ - Write idiomatic SQL for the target dialect: {dialect}.
15
+ - Do not run the query. Only produce it.
16
+ - Output ONLY the SQL query. No explanation, no comment, no markdown fences.
17
+
18
+ USER:
19
+ Target SQL dialect: {dialect}
20
+
21
+ Reduced schema (relevant subset):
22
+ --------------------------------
23
+ {linked_schema}
24
+ --------------------------------
25
+
26
+ Linking analysis (reasoning from the previous step — follow this logic):
27
+ {rationale}
28
+
29
+ Relevant columns:
30
+ {columns}
31
+
32
+ Suggested joins:
33
+ {joins}
34
+
35
+ Detected entities: {entities}
36
+ Filter hints: {filters}
37
+
38
+ User request:
39
+ "{request}"
40
+
41
+ Write the SQL query that answers the request.
@@ -1,9 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: text2sql-engine
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Schema-agnostic, config-driven Text-to-SQL library (2-stage LLM pipeline). Produces a SQL string; never connects to or executes against a database.
5
- Author: stajyer14
5
+ Author: Mehmet Kaan Durupunar
6
6
  License: MIT
7
+ Project-URL: Homepage, https://github.com/defectGI/sqlretrieve
8
+ Project-URL: Repository, https://github.com/defectGI/sqlretrieve
9
+ Project-URL: Issues, https://github.com/defectGI/sqlretrieve/issues
7
10
  Keywords: text-to-sql,nl2sql,llm,sql-generation,schema-linking
8
11
  Classifier: Development Status :: 4 - Beta
9
12
  Classifier: Intended Audience :: Developers
@@ -67,8 +70,11 @@ user request
67
70
  reduces the schema to the relevant part and returns structured JSON. Output is
68
71
  forced via `response_format` (OpenAI) or tool-calling (Anthropic), with
69
72
  strict-JSON parsing and retry as a fallback.
70
- - **Stage 2 (generation)** takes the request and that reduced subset. It writes
71
- SQL in the target dialect, plus a short explanation.
73
+ - **Stage 2 (generation)** takes the request, that reduced subset, and Stage 1's
74
+ reasoning (rationale, chosen joins, column reasons). It follows that logic and
75
+ writes SQL in the target dialect. Two output modes (config `output_mode`):
76
+ `structured` forces JSON with `sql` + `explanation`; `raw` asks for plain SQL
77
+ text, for specialized text-to-SQL models.
72
78
  - The two stages can use **different providers and models**. For example a cheap
73
79
  general model for linking, a stronger SQL model for generation.
74
80
 
@@ -165,8 +171,9 @@ No magic numbers in code. Every tunable is here.
165
171
  | `temperature` | float | `0.0` | Sampling temperature. |
166
172
  | `top_p` | float | `1.0` | Nucleus-sampling cutoff. |
167
173
  | `max_tokens` | int | `1024` | Max tokens for the SQL response. |
168
- | `prompt_template` | string | `generation.txt` | Template file, looked up in `PROMPT_DIR`. |
174
+ | `prompt_template` | string | `generation.txt` | Template file, looked up in `PROMPT_DIR`. In `raw` mode, defaults to `generation_raw.txt` when unset. |
169
175
  | `timeout_seconds` | float | `60` | Per-request timeout. |
176
+ | `output_mode` | string | `structured` | `structured`: force JSON with `sql` + `explanation`, reliable parsing, best for general models. `raw`: ask for plain SQL text (no explanation), better for specialized text-to-SQL models trained to emit SQL only. |
170
177
 
171
178
  #### `[retry]` — shared by both stages
172
179
 
@@ -1,16 +1,17 @@
1
- text2sql/__init__.py,sha256=EUP3cVW8vLecps3wqmPqqr6Apaht2tD9QsfdjP5-CQM,1442
2
- text2sql/config.py,sha256=jCpdUogpzRmkL5kN6CPqYXhUNhRA7EdaCFlCY65QnLA,7709
1
+ text2sql/__init__.py,sha256=dwQ98mfnAHRbUhKmOEnC0BcGK-8Slxosi8hqDgpkheM,1442
2
+ text2sql/config.py,sha256=6snv99rf8jf8NtD3xetSrvIaltbLyq2eoISoMoPadSw,8503
3
3
  text2sql/errors.py,sha256=Y5ORy7g_UsFvDJ2KorB2JFvTyOBqmrPv9MWc8Cl9MI8,1052
4
4
  text2sql/logging_utils.py,sha256=hiEH1SDqP16kctUj4uPP0tbXdrCO9AlRcdS-mHYDg5s,1633
5
5
  text2sql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  text2sql/types.py,sha256=MxcdHP7Gnftk1yKdcBQKaVVyeqRnBu5kxbhSZ2xJJ80,3532
7
7
  text2sql/pipeline/__init__.py,sha256=rjEOi4U9C-SKP15cyKPdvG_EZBOW0VW01LouS3PJVdY,245
8
- text2sql/pipeline/generation.py,sha256=LpnsKmSgu4Gfg-nHCCk6akg7ToI-G9Vk0LaVRn9WK5Y,3635
8
+ text2sql/pipeline/generation.py,sha256=M9wehTcMAq1QoK1nnQ4SJd1mszSfXs9E06l26IXpKNw,5750
9
9
  text2sql/pipeline/json_utils.py,sha256=92viA3xyw_GMF_nKdjSPgAyQ8iBUZgnyNRAoyWC5ZlE,3145
10
10
  text2sql/pipeline/linking.py,sha256=U28LOcWJn3cItwAsv2fG4fYv9KcJ80XmP1Fi8nNx4qc,6966
11
11
  text2sql/pipeline/pipeline.py,sha256=TE0cHSEJyeY43P89HsQDbnPGSfgRQmtw7KZAq-Yjj1U,5675
12
12
  text2sql/prompts/__init__.py,sha256=HfeflfAGsZl3xHnNrmklTP6K_8EKxX6vWJrayq6QuEQ,3315
13
- text2sql/prompts/generation.txt,sha256=r4125WCr7gsJIzTa5wZTAmbTyn5WvP3QrfGf4CWNP_w,849
13
+ text2sql/prompts/generation.txt,sha256=th97BZsHFlRtH30OqHj4DY_BooCsa7Zad9EoXC9M_cM,1381
14
+ text2sql/prompts/generation_raw.txt,sha256=EsKLl7WrNWQzcoxAFW9l6yucUtBa7sIimCsvIjRx7ZI,1321
14
15
  text2sql/prompts/linking.txt,sha256=nLPSkaq3PiWiJ7wXLeD0BvK_-rR3hhc_tLhZ-daPnGY,889
15
16
  text2sql/providers/__init__.py,sha256=R5a-YKtyaUFpkVJGWrmhDGyRHeh84gA3F7nEH57dSGo,345
16
17
  text2sql/providers/anthropic_provider.py,sha256=Zhh8zM6EfHqkjTgNmhYKdZLHQ69b0Pu2-5WbCW2rD6s,4342
@@ -22,8 +23,8 @@ text2sql/schema/file_provider.py,sha256=Nv9x2-Eh9mXISk5XvUQaLfagth2s3LbX5F7jWp-o
22
23
  text2sql/schema/models.py,sha256=yX5zdKbTuy-g-nkwT0v-0HUTK81jBRoabV-OC-kD-JI,2263
23
24
  text2sql/schema/provider.py,sha256=JPMRsjRgEB4RdQR_pFwbP2LwLIXZhQVWSQPoYzaXC7s,798
24
25
  text2sql/schema/serialize.py,sha256=_2MeA1IwDJ51-69PXyqXBSFZSyzovbqJkRIMpekkfJA,1833
25
- text2sql_engine-0.1.0.dist-info/licenses/LICENSE,sha256=dzrVwSmgUgCDYwDn21Job7Yb4huyHjC74evyzsHXas8,1078
26
- text2sql_engine-0.1.0.dist-info/METADATA,sha256=Cni4NycxDnoS3HgP5eYTRiUXgOmnLhSYBI27LTBm08U,12302
27
- text2sql_engine-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
28
- text2sql_engine-0.1.0.dist-info/top_level.txt,sha256=ZONWO1r8wsWpyHhF5qPzAjnsNoCEhwZ2Z-M_V8nKALc,9
29
- text2sql_engine-0.1.0.dist-info/RECORD,,
26
+ text2sql_engine-0.2.0.dist-info/licenses/LICENSE,sha256=qfdfVnpb5NOM3-SK13PnmWagjCLy5sE9ORlgOGXc8hU,1078
27
+ text2sql_engine-0.2.0.dist-info/METADATA,sha256=Xn9bMUbUlTrirl1JWpZ99bOrfZRZzK2IdDx8bQVmRFw,13061
28
+ text2sql_engine-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
29
+ text2sql_engine-0.2.0.dist-info/top_level.txt,sha256=ZONWO1r8wsWpyHhF5qPzAjnsNoCEhwZ2Z-M_V8nKALc,9
30
+ text2sql_engine-0.2.0.dist-info/RECORD,,
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 text2sql contributors
3
+ Copyright (c) 2026 Mehmet Kaan Durupunar
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal