gaard-core 0.2.20__tar.gz → 0.2.21__tar.gz

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.
Files changed (66) hide show
  1. {gaard_core-0.2.20 → gaard_core-0.2.21}/PKG-INFO +2 -2
  2. {gaard_core-0.2.20 → gaard_core-0.2.21}/pyproject.toml +2 -2
  3. gaard_core-0.2.21/src/gaard_core/conversation_context/llm_classifier.py +187 -0
  4. gaard_core-0.2.21/src/gaard_core/conversation_context/mock_classifier.py +145 -0
  5. gaard_core-0.2.21/src/gaard_core/prompt_compiler/conversation_context_prompt.py +121 -0
  6. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/result_interpretation_prompt.py +1 -1
  7. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/sql_generation_prompt.py +2 -17
  8. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_pipeline/models.py +3 -2
  9. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_pipeline/pipeline.py +4 -1
  10. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core.egg-info/PKG-INFO +2 -2
  11. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core.egg-info/requires.txt +1 -1
  12. gaard_core-0.2.21/tests/test_conversation_context_classifier.py +129 -0
  13. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_query_pipeline.py +21 -0
  14. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_sql_generation_prompt_compiler.py +0 -19
  15. gaard_core-0.2.20/src/gaard_core/conversation_context/llm_classifier.py +0 -165
  16. gaard_core-0.2.20/src/gaard_core/conversation_context/mock_classifier.py +0 -29
  17. gaard_core-0.2.20/src/gaard_core/prompt_compiler/conversation_context_prompt.py +0 -79
  18. gaard_core-0.2.20/tests/test_conversation_context_classifier.py +0 -124
  19. {gaard_core-0.2.20 → gaard_core-0.2.21}/README.md +0 -0
  20. {gaard_core-0.2.20 → gaard_core-0.2.21}/setup.cfg +0 -0
  21. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/__init__.py +0 -0
  22. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/conversation_context/__init__.py +0 -0
  23. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/errors.py +0 -0
  24. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/execution/__init__.py +0 -0
  25. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/execution/mock_executor.py +0 -0
  26. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/json_utils.py +0 -0
  27. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/llm_output.py +0 -0
  28. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/__init__.py +0 -0
  29. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/intent_classification_prompt.py +0 -0
  30. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/models.py +0 -0
  31. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/result_classification_prompt.py +0 -0
  32. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/prompt_compiler/schema_formatter.py +0 -0
  33. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/py.typed +0 -0
  34. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_intent/__init__.py +0 -0
  35. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_intent/llm_classifier.py +0 -0
  36. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_intent/mock_classifier.py +0 -0
  37. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_pipeline/__init__.py +0 -0
  38. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_pipeline/llm_sql_generator.py +0 -0
  39. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/query_pipeline/mock_sql_generator.py +0 -0
  40. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_classifier/__init__.py +0 -0
  41. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_classifier/llm_classifier.py +0 -0
  42. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_classifier/mock_classifier.py +0 -0
  43. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_interpreter/__init__.py +0 -0
  44. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_interpreter/llm_interpreter.py +0 -0
  45. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/result_interpreter/mock_interpreter.py +0 -0
  46. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/schema/__init__.py +0 -0
  47. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/schema/cache.py +0 -0
  48. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/schema/context.py +0 -0
  49. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/schema/models.py +0 -0
  50. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/sql_validator/__init__.py +0 -0
  51. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core/sql_validator/select_only.py +0 -0
  52. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core.egg-info/SOURCES.txt +0 -0
  53. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core.egg-info/dependency_links.txt +0 -0
  54. {gaard_core-0.2.20 → gaard_core-0.2.21}/src/gaard_core.egg-info/top_level.txt +0 -0
  55. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_json_utils.py +0 -0
  56. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_llm_output.py +0 -0
  57. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_llm_query_intent_classifier.py +0 -0
  58. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_llm_result_classifier.py +0 -0
  59. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_llm_result_interpreter.py +0 -0
  60. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_llm_sql_generator.py +0 -0
  61. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_result_classification_prompt_compiler.py +0 -0
  62. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_result_interpretation_prompt_compiler.py +0 -0
  63. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_schema_context_cache.py +0 -0
  64. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_schema_context_service.py +0 -0
  65. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_schema_prompt_formatter.py +0 -0
  66. {gaard_core-0.2.20 → gaard_core-0.2.21}/tests/test_sql_validator.py +0 -0
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gaard-core
3
- Version: 0.2.20
3
+ Version: 0.2.21
4
4
  Summary: Core GAARD query pipeline, prompt compiler, policies and SQL validation
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.20
7
+ Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.21
8
8
  Requires-Dist: pydantic>=2.7.0
9
9
  Requires-Dist: sqlglot>=25.0.0
10
10
  Provides-Extra: dev
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gaard-core"
7
- version = "0.2.20"
7
+ version = "0.2.21"
8
8
  description = "Core GAARD query pipeline, prompt compiler, policies and SQL validation"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
11
11
  dependencies = [
12
- "gaard-plugin-api>=0.2.20,<0.3.0",
12
+ "gaard-plugin-api>=0.2.21,<0.3.0",
13
13
  "pydantic>=2.7.0",
14
14
  "sqlglot>=25.0.0",
15
15
  ]
@@ -0,0 +1,187 @@
1
+ import json
2
+ from typing import Any, Protocol, cast
3
+
4
+ from gaard_llm.openai_compatible.client import OpenAICompatibleClient
5
+ from gaard_llm.providers.models import ChatCompletionRequest, ChatMessage
6
+
7
+ from gaard_core.llm_output import remove_thinking_blocks
8
+ from gaard_core.prompt_compiler.conversation_context_prompt import (
9
+ ConversationContextPromptCompiler,
10
+ )
11
+ from gaard_core.prompt_compiler.models import CompiledPrompt
12
+ from gaard_core.query_pipeline.models import (
13
+ ConversationContextClassification,
14
+ ConversationContextDecision,
15
+ QueryRequest,
16
+ )
17
+
18
+
19
+ class ConversationContextPromptCompilerProtocol(Protocol):
20
+ def compile(
21
+ self,
22
+ request: QueryRequest,
23
+ conversation_context: dict[str, Any],
24
+ ) -> CompiledPrompt:
25
+ pass
26
+
27
+
28
+ class LlmConversationContextClassifier:
29
+ def __init__(
30
+ self,
31
+ client: OpenAICompatibleClient,
32
+ model: str,
33
+ extra_body: dict[str, Any] | None = None,
34
+ prompt_compiler: ConversationContextPromptCompilerProtocol | None = None,
35
+ ) -> None:
36
+ self.client = client
37
+ self.model = model
38
+ self.extra_body = extra_body or {}
39
+ self.prompt_compiler = prompt_compiler or ConversationContextPromptCompiler()
40
+
41
+ def classify(
42
+ self,
43
+ request: QueryRequest,
44
+ conversation_context: dict[str, Any],
45
+ ) -> ConversationContextClassification:
46
+ compiled_prompt = self.prompt_compiler.compile(
47
+ request=request,
48
+ conversation_context=conversation_context,
49
+ )
50
+ response = self.client.create_chat_completion(
51
+ ChatCompletionRequest(
52
+ model=self.model,
53
+ temperature=0.0,
54
+ extra_body=self.extra_body,
55
+ messages=[
56
+ ChatMessage(role="system", content=compiled_prompt.system_prompt),
57
+ ChatMessage(role="user", content=compiled_prompt.user_prompt),
58
+ ],
59
+ )
60
+ )
61
+
62
+ classification = parse_conversation_context_classification(response.content)
63
+ if (
64
+ classification.decision == ConversationContextDecision.NEW_TOPIC
65
+ and not classification.standalone_question
66
+ ):
67
+ classification = classification.model_copy(
68
+ update={"standalone_question": request.question}
69
+ )
70
+ if (
71
+ classification.decision == ConversationContextDecision.FOLLOW_UP
72
+ and not classification.standalone_question
73
+ and classification.model_response.get("current_question_is_standalone") is True
74
+ ):
75
+ classification = classification.model_copy(
76
+ update={"standalone_question": request.question}
77
+ )
78
+ return classification.model_copy(
79
+ update={
80
+ "prompt": {
81
+ "system_prompt": compiled_prompt.system_prompt,
82
+ "user_prompt": compiled_prompt.user_prompt,
83
+ "metadata": compiled_prompt.metadata,
84
+ },
85
+ "source": "llm",
86
+ }
87
+ )
88
+
89
+
90
+ def parse_conversation_context_classification(
91
+ value: str,
92
+ ) -> ConversationContextClassification:
93
+ cleaned = remove_thinking_blocks(value).strip()
94
+ if cleaned.startswith("```json"):
95
+ cleaned = cleaned.removeprefix("```json").strip()
96
+ if cleaned.startswith("```"):
97
+ cleaned = cleaned.removeprefix("```").strip()
98
+ if cleaned.endswith("```"):
99
+ cleaned = cleaned.removesuffix("```").strip()
100
+
101
+ try:
102
+ payload = json.loads(cleaned)
103
+ except json.JSONDecodeError:
104
+ payload = {"decision": cleaned}
105
+
106
+ if not isinstance(payload, dict):
107
+ return ConversationContextClassification()
108
+
109
+ decision = parse_conversation_context_decision(
110
+ payload.get("decision"),
111
+ continuation_value=payload.get("is_continuation"),
112
+ )
113
+ return ConversationContextClassification(
114
+ decision=decision,
115
+ confidence=parse_confidence(payload.get("confidence")),
116
+ standalone_question=str(payload.get("standalone_question") or "").strip(),
117
+ reason=str(payload.get("reason") or ""),
118
+ model_response=payload,
119
+ )
120
+
121
+
122
+ def parse_conversation_context_decision(
123
+ value: object,
124
+ *,
125
+ continuation_value: object | None = None,
126
+ ) -> ConversationContextDecision:
127
+ if value is None:
128
+ continuation_decision = parse_continuation_decision(continuation_value)
129
+ if continuation_decision is not None:
130
+ return continuation_decision
131
+
132
+ if not isinstance(value, str):
133
+ return ConversationContextDecision.AMBIGUOUS
134
+
135
+ normalized = value.strip().lower().replace(" ", "_").replace("-", "_")
136
+ aliases = {
137
+ "no": ConversationContextDecision.NEW_TOPIC,
138
+ "nie": ConversationContextDecision.NEW_TOPIC,
139
+ "false": ConversationContextDecision.NEW_TOPIC,
140
+ "new": ConversationContextDecision.NEW_TOPIC,
141
+ "new_question": ConversationContextDecision.NEW_TOPIC,
142
+ "newtopic": ConversationContextDecision.NEW_TOPIC,
143
+ "yes": ConversationContextDecision.FOLLOW_UP,
144
+ "tak": ConversationContextDecision.FOLLOW_UP,
145
+ "true": ConversationContextDecision.FOLLOW_UP,
146
+ "continue": ConversationContextDecision.FOLLOW_UP,
147
+ "continuation": ConversationContextDecision.FOLLOW_UP,
148
+ "followup": ConversationContextDecision.FOLLOW_UP,
149
+ "follow_up_question": ConversationContextDecision.FOLLOW_UP,
150
+ "unclear": ConversationContextDecision.AMBIGUOUS,
151
+ "needs_clarification": ConversationContextDecision.AMBIGUOUS,
152
+ }
153
+ if normalized in aliases:
154
+ return aliases[normalized]
155
+
156
+ for item in ConversationContextDecision:
157
+ if normalized == item.value:
158
+ return item
159
+
160
+ return ConversationContextDecision.AMBIGUOUS
161
+
162
+
163
+ def parse_continuation_decision(value: object) -> ConversationContextDecision | None:
164
+ if isinstance(value, bool):
165
+ return (
166
+ ConversationContextDecision.FOLLOW_UP
167
+ if value
168
+ else ConversationContextDecision.NEW_TOPIC
169
+ )
170
+ if not isinstance(value, str):
171
+ return None
172
+
173
+ normalized = value.strip().lower()
174
+ if normalized in {"yes", "y", "true", "tak", "t"}:
175
+ return ConversationContextDecision.FOLLOW_UP
176
+ if normalized in {"no", "n", "false", "nie"}:
177
+ return ConversationContextDecision.NEW_TOPIC
178
+ return None
179
+
180
+
181
+ def parse_confidence(value: object) -> float:
182
+ try:
183
+ confidence = float(cast(Any, value))
184
+ except (TypeError, ValueError):
185
+ return 0.0
186
+
187
+ return max(0.0, min(1.0, confidence))
@@ -0,0 +1,145 @@
1
+ import re
2
+ from typing import Any
3
+
4
+ from gaard_core.query_pipeline.models import (
5
+ ConversationContextClassification,
6
+ ConversationContextDecision,
7
+ QueryRequest,
8
+ )
9
+
10
+ FOLLOW_UP_PREFIXES = (
11
+ "a ",
12
+ "and ",
13
+ "oraz ",
14
+ "to samo",
15
+ "tak samo",
16
+ "dla ",
17
+ "w ",
18
+ "za ",
19
+ "porównaj",
20
+ "porownaj",
21
+ "compare",
22
+ "same",
23
+ )
24
+
25
+ AMBIGUOUS_TERMS = (
26
+ "to",
27
+ "tego",
28
+ "tamto",
29
+ "tamte",
30
+ "them",
31
+ "it",
32
+ "that",
33
+ )
34
+
35
+ RESULT_REFERENCE_TERMS = (
36
+ "ich",
37
+ "nich",
38
+ "tych",
39
+ "te",
40
+ "tej",
41
+ "tego",
42
+ "their",
43
+ "them",
44
+ "these",
45
+ "those",
46
+ )
47
+
48
+ PROJECTION_COMMAND_PREFIXES = (
49
+ "podaj ",
50
+ "pokaż ",
51
+ "pokaz ",
52
+ "wypisz ",
53
+ "wyświetl ",
54
+ "wyswietl ",
55
+ "show ",
56
+ "list ",
57
+ "give ",
58
+ "return ",
59
+ )
60
+
61
+
62
+ class MockConversationContextClassifier:
63
+ def classify(
64
+ self,
65
+ request: QueryRequest,
66
+ conversation_context: dict[str, Any],
67
+ ) -> ConversationContextClassification:
68
+ turns = conversation_context.get("turns") or []
69
+ if not turns:
70
+ return ConversationContextClassification(
71
+ decision=ConversationContextDecision.NEW_TOPIC,
72
+ confidence=1.0,
73
+ standalone_question=request.question,
74
+ reason="No previous turns are available.",
75
+ source="mock",
76
+ )
77
+
78
+ question = request.question.strip()
79
+ normalized = question.lower()
80
+ if looks_like_follow_up(normalized) or looks_like_projection_follow_up(normalized):
81
+ previous = latest_question(turns)
82
+ standalone = combine_follow_up(previous, question)
83
+ return ConversationContextClassification(
84
+ decision=ConversationContextDecision.FOLLOW_UP,
85
+ confidence=0.8,
86
+ standalone_question=standalone,
87
+ reason="The question appears to continue the previous data question.",
88
+ source="mock",
89
+ )
90
+
91
+ if normalized in AMBIGUOUS_TERMS or re.fullmatch(
92
+ r"(a )?(co|what|why|dlaczego)\??", normalized
93
+ ):
94
+ return ConversationContextClassification(
95
+ decision=ConversationContextDecision.AMBIGUOUS,
96
+ confidence=0.45,
97
+ standalone_question="",
98
+ reason="The question is too short to safely resolve from context.",
99
+ source="mock",
100
+ )
101
+
102
+ return ConversationContextClassification(
103
+ decision=ConversationContextDecision.NEW_TOPIC,
104
+ confidence=0.9,
105
+ standalone_question=question,
106
+ reason="The question is self-contained.",
107
+ source="mock",
108
+ )
109
+
110
+
111
+ def looks_like_follow_up(normalized_question: str) -> bool:
112
+ return any(normalized_question.startswith(prefix) for prefix in FOLLOW_UP_PREFIXES)
113
+
114
+
115
+ def looks_like_projection_follow_up(normalized_question: str) -> bool:
116
+ if not any(normalized_question.startswith(prefix) for prefix in PROJECTION_COMMAND_PREFIXES):
117
+ return False
118
+
119
+ tokens = set(re.findall(r"[\wąćęłńóśźż]+", normalized_question))
120
+ return bool(tokens & set(RESULT_REFERENCE_TERMS))
121
+
122
+
123
+ def latest_question(turns: list[Any]) -> str:
124
+ for turn in reversed(turns):
125
+ if not isinstance(turn, dict):
126
+ continue
127
+ question = str(
128
+ turn.get("standalone_question")
129
+ or turn.get("question")
130
+ or turn.get("original_question")
131
+ or ""
132
+ ).strip()
133
+ if question:
134
+ return question
135
+
136
+ return ""
137
+
138
+
139
+ def combine_follow_up(previous_question: str, question: str) -> str:
140
+ previous = previous_question.strip().rstrip(".?")
141
+ current = question.strip().rstrip(".?")
142
+ if not previous:
143
+ return question.strip()
144
+
145
+ return f"{previous}; kontynuacja: {current}?"
@@ -0,0 +1,121 @@
1
+ from typing import Any
2
+
3
+ from gaard_core.json_utils import json_dumps
4
+ from gaard_core.prompt_compiler.models import CompiledPrompt
5
+ from gaard_core.query_pipeline.models import ConversationContextDecision, QueryRequest
6
+
7
+
8
+ class ConversationContextPromptCompiler:
9
+ def compile(
10
+ self,
11
+ request: QueryRequest,
12
+ conversation_context: dict[str, Any],
13
+ ) -> CompiledPrompt:
14
+ recent_turns = self._recent_turns(conversation_context)
15
+ payload = {
16
+ "turn_t_minus_2": recent_turns[0] if len(recent_turns) == 2 else {},
17
+ "turn_t_minus_1": recent_turns[-1] if recent_turns else {},
18
+ "turn_t": {
19
+ "question": request.question,
20
+ "datasource_id": request.datasource_id,
21
+ "datasource_ids": request.datasource_ids,
22
+ },
23
+ }
24
+
25
+ return CompiledPrompt(
26
+ system_prompt=self._build_system_prompt(),
27
+ user_prompt=self._build_user_prompt(payload),
28
+ metadata={
29
+ "allowed_decisions": [item.value for item in ConversationContextDecision],
30
+ "decision_task": "logical_continuation_yes_no",
31
+ },
32
+ )
33
+
34
+ def _recent_turns(self, conversation_context: dict[str, Any]) -> list[dict[str, Any]]:
35
+ turns = [
36
+ turn for turn in conversation_context.get("turns", []) if isinstance(turn, dict)
37
+ ][-2:]
38
+ labels = ["t-2", "t-1"] if len(turns) == 2 else ["t-1"]
39
+ return [
40
+ {
41
+ "label": label,
42
+ "question": str(turn.get("question") or ""),
43
+ "standalone_question": str(turn.get("standalone_question") or ""),
44
+ "answer": str(turn.get("answer") or ""),
45
+ "sql": str(turn.get("sql") or ""),
46
+ "context_decision": str(turn.get("context_decision") or ""),
47
+ "context_reason": str(turn.get("context_reason") or ""),
48
+ }
49
+ for label, turn in zip(labels, turns, strict=False)
50
+ ]
51
+
52
+ def _build_system_prompt(self) -> str:
53
+ return """You are GAARD Conversation Context Classification.
54
+
55
+ Your task is to decide whether the current user data question (turn t) is a
56
+ logical continuation of the recent conversation turns (t-2 and t-1).
57
+
58
+ Use the previous question-answer pairs as conversation evidence. Do not classify
59
+ by rigid prefix or keyword rules. Decide semantically whether turn t depends on,
60
+ compares with, narrows, broadens, or otherwise continues the immediately
61
+ preceding analytical thread.
62
+
63
+ Allowed decisions:
64
+ - new_topic: answer "no" to logical continuation. The question starts a new analytical thread.
65
+ - follow_up: answer "yes" to logical continuation. The question continues the
66
+ recent thread and can be executed safely.
67
+ - ambiguous: the question appears to continue the thread, but required entities,
68
+ filters, date ranges, or datasource scope cannot be inferred safely.
69
+
70
+ Decision rules:
71
+ 1. First answer the yes/no question: is turn t a logical continuation of t-1/t-2?
72
+ 2. A question can be a logical continuation even when it is already
73
+ self-contained. In that case use follow_up, set
74
+ current_question_is_standalone to true, and set standalone_question to the
75
+ current question.
76
+ 3. If the answer is no, use new_topic and set standalone_question to the current question.
77
+ 4. If the answer is yes and the current question is elliptical, rewrite it as a
78
+ standalone data question using t-1/t-2.
79
+ 5. Use ambiguous only when the answer is yes but the continuation cannot be
80
+ rewritten or executed safely without asking the user.
81
+ 6. Treat detail/projection requests about the previous result as follow_up when
82
+ the previous turn defines the result set. If the previous question counted,
83
+ grouped, or filtered records and the user now asks for descriptions, names,
84
+ statuses, fields, details, or values for those same records, rewrite by
85
+ preserving the previous filters/date range/datasource and changing only the
86
+ returned fields.
87
+ 7. Do not mark a projection/detail follow-up ambiguous merely because the
88
+ previous answer did not expose row ids. The previous standalone question and
89
+ SQL are enough context for the next SQL generation step.
90
+ 8. Never include rows or sensitive data in the standalone question.
91
+
92
+ Output rules:
93
+ - Return only a JSON object.
94
+ - Do not include markdown.
95
+ - Do not include reasoning outside the JSON.
96
+ - Do not include <think> blocks.
97
+ - Use exactly this JSON shape:
98
+ {
99
+ "is_continuation": false,
100
+ "decision": "new_topic",
101
+ "current_question_is_standalone": true,
102
+ "confidence": 0.0,
103
+ "standalone_question": "rewritten or current question",
104
+ "reason": "short reason"
105
+ }
106
+ """
107
+
108
+ def _build_user_prompt(self, payload: dict[str, Any]) -> str:
109
+ return f"""Decide whether turn t is a logical continuation of turns t-2 and t-1.
110
+
111
+ Input JSON:
112
+ {json_dumps(payload, ensure_ascii=False, indent=2)}
113
+
114
+ Return one JSON object with:
115
+ - is_continuation: boolean yes/no answer to the logical-continuation question
116
+ - decision: one of {", ".join(item.value for item in ConversationContextDecision)}
117
+ - current_question_is_standalone: boolean
118
+ - confidence: number from 0 to 1
119
+ - standalone_question: required for follow_up and new_topic; empty only for ambiguous
120
+ - reason: short explanation
121
+ """
@@ -35,7 +35,7 @@ class ResultInterpretationPromptCompiler:
35
35
  Your task is to explain SQL query results to the user.
36
36
 
37
37
  Rules:
38
- - Answer in the same language as the user's question.
38
+ - Answer entirely in the same language as the user's question. Infer it only from the question, regardless of the language of SQL, column names, or returned values.
39
39
  - Pay attention to correct user's language grammar and plural forms.
40
40
  - Use only the data provided in the result.
41
41
  - Do not invent facts.
@@ -3,21 +3,6 @@ from gaard_core.prompt_compiler.models import CompiledPrompt, SqlGenerationPromp
3
3
  from gaard_core.prompt_compiler.schema_formatter import SchemaPromptFormatter
4
4
 
5
5
 
6
- def sql_row_limit_instruction(dialect: str, max_rows: int) -> str:
7
- normalized = dialect.strip().lower()
8
- if normalized in {"tsql", "mssql", "sqlserver"}:
9
- syntax = f"SELECT TOP ({max_rows}); never use LIMIT in T-SQL"
10
- elif normalized in {"oracle", "db2"}:
11
- syntax = f"FETCH FIRST {max_rows} ROWS ONLY; never use LIMIT"
12
- elif normalized == "teradata":
13
- syntax = f"SELECT TOP {max_rows}"
14
- elif normalized in {"sqlite", "postgres", "postgresql", "mysql", "duckdb"}:
15
- syntax = f"LIMIT {max_rows}"
16
- else:
17
- syntax = f"the native row-limiting syntax of the {dialect} dialect"
18
- return f"When the query may return many rows, return at most {max_rows} rows using {syntax}."
19
-
20
-
21
6
  class SqlGenerationPromptCompiler:
22
7
  def __init__(self, schema_formatter: SchemaPromptFormatter | None = None) -> None:
23
8
  self.schema_formatter = schema_formatter or SchemaPromptFormatter()
@@ -90,8 +75,8 @@ Query construction rules:
90
75
  3. If the user asks for both a total and a breakdown, prefer one SELECT statement that returns grouped rows or conditional aggregate columns.
91
76
  4. Do not solve one user question by generating multiple separate SELECT statements.
92
77
  5. Prefer explicit column names over SELECT *.
93
- 6. {sql_row_limit_instruction(dialect, max_rows)}
94
- 7. Do not add a row limit to pure aggregate queries that return a single row.
78
+ 6. Add LIMIT {max_rows} when the query may return many rows.
79
+ 7. Do not add LIMIT to pure aggregate queries that return a single row, unless it is already useful for the dialect or safety.
95
80
  8. Use clear aliases for computed expressions.
96
81
  9. When the query uses more than one table, every table must have a short, stable alias.
97
82
  10. When the query uses more than one table, every column reference must be qualified with the correct table alias in SELECT, JOIN, WHERE, GROUP BY, HAVING and ORDER BY.
@@ -1,7 +1,7 @@
1
1
  from enum import StrEnum
2
2
  from typing import Any
3
3
 
4
- from pydantic import BaseModel, Field
4
+ from pydantic import BaseModel, Field, PrivateAttr
5
5
 
6
6
 
7
7
  class OutputClassification(StrEnum):
@@ -35,10 +35,10 @@ class ContextMode(StrEnum):
35
35
  class ConversationContextDecision(StrEnum):
36
36
  NEW_TOPIC = "new_topic"
37
37
  FOLLOW_UP = "follow_up"
38
+ AMBIGUOUS = "ambiguous"
38
39
 
39
40
 
40
41
  class ConversationContextClassification(BaseModel):
41
- turn_id: str = ""
42
42
  decision: ConversationContextDecision = ConversationContextDecision.NEW_TOPIC
43
43
  confidence: float = 0.0
44
44
  standalone_question: str = ""
@@ -56,6 +56,7 @@ class QueryRequest(BaseModel):
56
56
  interpret: bool = True
57
57
  conversation_id: str | None = None
58
58
  context_mode: ContextMode = ContextMode.AUTO
59
+ _original_question: str | None = PrivateAttr(default=None)
59
60
 
60
61
 
61
62
  class GeneratedSql(BaseModel):
@@ -123,9 +123,12 @@ class QueryPipeline:
123
123
  metadata=metadata,
124
124
  )
125
125
 
126
+ answer_request = request
127
+ if request._original_question is not None:
128
+ answer_request = request.model_copy(update={"question": request._original_question})
126
129
  try:
127
130
  answer = self.interpreter.interpret(
128
- request=request,
131
+ request=answer_request,
129
132
  result=result,
130
133
  sql=generated_sql.sql,
131
134
  )
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gaard-core
3
- Version: 0.2.20
3
+ Version: 0.2.21
4
4
  Summary: Core GAARD query pipeline, prompt compiler, policies and SQL validation
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.20
7
+ Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.21
8
8
  Requires-Dist: pydantic>=2.7.0
9
9
  Requires-Dist: sqlglot>=25.0.0
10
10
  Provides-Extra: dev
@@ -1,4 +1,4 @@
1
- gaard-plugin-api<0.3.0,>=0.2.20
1
+ gaard-plugin-api<0.3.0,>=0.2.21
2
2
  pydantic>=2.7.0
3
3
  sqlglot>=25.0.0
4
4