gaard-api 0.2.18__tar.gz → 0.2.20__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 (81) hide show
  1. {gaard_api-0.2.18/src/gaard_api.egg-info → gaard_api-0.2.20}/PKG-INFO +23 -5
  2. {gaard_api-0.2.18 → gaard_api-0.2.20}/README.md +18 -0
  3. {gaard_api-0.2.18 → gaard_api-0.2.20}/pyproject.toml +5 -5
  4. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/database.py +13 -0
  5. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/defaults.py +19 -71
  6. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/prompt_runtime.py +39 -39
  7. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/services.py +16 -1
  8. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/analysis.py +60 -80
  9. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/query.py +85 -700
  10. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/conversations.py +82 -191
  11. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/main.py +1 -1
  12. {gaard_api-0.2.18 → gaard_api-0.2.20/src/gaard_api.egg-info}/PKG-INFO +23 -5
  13. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api.egg-info/requires.txt +4 -4
  14. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_admin_api.py +157 -1
  15. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_analysis_api.py +43 -3
  16. gaard_api-0.2.20/tests/test_conversation_api.py +462 -0
  17. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_prompt_runtime.py +5 -4
  18. gaard_api-0.2.18/tests/test_conversation_api.py +0 -616
  19. {gaard_api-0.2.18 → gaard_api-0.2.20}/MANIFEST.in +0 -0
  20. {gaard_api-0.2.18 → gaard_api-0.2.20}/setup.cfg +0 -0
  21. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/__init__.py +0 -0
  22. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/__init__.py +0 -0
  23. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/database_initial.sql +0 -0
  24. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/database_legacy_updates.sql +0 -0
  25. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/database_updates.sql +0 -0
  26. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/metadata.py +0 -0
  27. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/migration_runner.py +0 -0
  28. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/models.py +0 -0
  29. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin/security.py +0 -0
  30. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/getgaard.svg +0 -0
  31. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/identity.js +0 -0
  32. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/main.js +0 -0
  33. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/styles.css +0 -0
  34. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/vendor/gridstack/gridstack-all.js +0 -0
  35. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/assets/vendor/gridstack/gridstack.min.css +0 -0
  36. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/index.html +0 -0
  37. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/admin-web/package.json +0 -0
  38. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/analysis_findings.py +0 -0
  39. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/__init__.py +0 -0
  40. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/__init__.py +0 -0
  41. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/admin.py +0 -0
  42. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/dashboards.py +0 -0
  43. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/prompts.py +0 -0
  44. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api/v1/schema.py +0 -0
  45. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/api_registry.py +0 -0
  46. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/auth_dependencies.py +0 -0
  47. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/auth_hooks.py +0 -0
  48. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/cli.py +0 -0
  49. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/cli_commands.py +0 -0
  50. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/core/__init__.py +0 -0
  51. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/core/error_handlers.py +0 -0
  52. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/core/schema_cache.py +0 -0
  53. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/core/settings.py +0 -0
  54. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/example_data/__init__.py +0 -0
  55. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/example_data/medical_poc/__init__.py +0 -0
  56. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/example_data/medical_poc/schema.sql +0 -0
  57. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/example_data/medical_poc/seed.sql +0 -0
  58. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/example_database.py +0 -0
  59. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/extension_services.py +0 -0
  60. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/extensions.py +0 -0
  61. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/license.py +0 -0
  62. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/package_updates.py +0 -0
  63. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/py.typed +0 -0
  64. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/query_hooks.py +0 -0
  65. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/server_cli.py +0 -0
  66. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/siem.py +0 -0
  67. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api/tls_http.py +0 -0
  68. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api.egg-info/SOURCES.txt +0 -0
  69. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api.egg-info/dependency_links.txt +0 -0
  70. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api.egg-info/entry_points.txt +0 -0
  71. {gaard_api-0.2.18 → gaard_api-0.2.20}/src/gaard_api.egg-info/top_level.txt +0 -0
  72. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_api_cli.py +0 -0
  73. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_api_registry.py +0 -0
  74. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_database_migrations.py +0 -0
  75. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_error_handlers.py +0 -0
  76. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_license_api.py +0 -0
  77. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_license_service.py +0 -0
  78. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_query_error_messages.py +0 -0
  79. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_server_cli.py +0 -0
  80. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_settings.py +0 -0
  81. {gaard_api-0.2.18 → gaard_api-0.2.20}/tests/test_tls_http.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gaard-api
3
- Version: 0.2.18
3
+ Version: 0.2.20
4
4
  Summary: GAARD backend web services providing admin interface
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: gaard-core==0.2.17
8
- Requires-Dist: gaard-connectors==0.2.17
9
- Requires-Dist: gaard-llm==0.2.17
10
- Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.17
7
+ Requires-Dist: gaard-core==0.2.20
8
+ Requires-Dist: gaard-connectors==0.2.20
9
+ Requires-Dist: gaard-llm==0.2.20
10
+ Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.20
11
11
  Requires-Dist: fastapi>=0.111.0
12
12
  Requires-Dist: uvicorn[standard]>=0.30.0
13
13
  Requires-Dist: pydantic>=2.7.0
@@ -68,3 +68,21 @@ API is available at `http://localhost:8000` and the admin application at
68
68
  `http://localhost:8000/admin`.
69
69
 
70
70
  `gaard-api start` is an alias. `gaard admin` remains available for compatibility.
71
+
72
+ ## Conversation context
73
+
74
+ With `context_mode: "auto"`, each question stores a `new_topic` or `follow_up`
75
+ decision. The LLM receives all turns since the last `new_topic`, including that
76
+ question. For a follow-up, a separate LLM call compresses this context together
77
+ with the current question into one standalone sentence. Both calls use
78
+ temperature zero. The resulting sentence is saved before SQL or Analysis runs;
79
+ a new topic uses the current question as its context.
80
+
81
+ `GET /api/v1/conversations/{conversation_id}/turns/{turn_id}/context` returns
82
+ the saved execution-time snapshot as JSON with `context`, `context_decision`,
83
+ `conversation_id`, and `turn_id`. The IDs are available in the query response's
84
+ `metadata.conversation` object. This authenticated endpoint only allows the
85
+ conversation owner and never regenerates the context from later messages.
86
+
87
+ `context_mode: "new"` starts a new conversation; `"off"` remains stateless.
88
+ Mock mode does not perform semantic context classification.
@@ -29,3 +29,21 @@ API is available at `http://localhost:8000` and the admin application at
29
29
  `http://localhost:8000/admin`.
30
30
 
31
31
  `gaard-api start` is an alias. `gaard admin` remains available for compatibility.
32
+
33
+ ## Conversation context
34
+
35
+ With `context_mode: "auto"`, each question stores a `new_topic` or `follow_up`
36
+ decision. The LLM receives all turns since the last `new_topic`, including that
37
+ question. For a follow-up, a separate LLM call compresses this context together
38
+ with the current question into one standalone sentence. Both calls use
39
+ temperature zero. The resulting sentence is saved before SQL or Analysis runs;
40
+ a new topic uses the current question as its context.
41
+
42
+ `GET /api/v1/conversations/{conversation_id}/turns/{turn_id}/context` returns
43
+ the saved execution-time snapshot as JSON with `context`, `context_decision`,
44
+ `conversation_id`, and `turn_id`. The IDs are available in the query response's
45
+ `metadata.conversation` object. This authenticated endpoint only allows the
46
+ conversation owner and never regenerates the context from later messages.
47
+
48
+ `context_mode: "new"` starts a new conversation; `"off"` remains stateless.
49
+ Mock mode does not perform semantic context classification.
@@ -4,16 +4,16 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gaard-api"
7
- version = "0.2.18"
7
+ version = "0.2.20"
8
8
  description = "GAARD backend web services providing admin interface"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
11
11
 
12
12
  dependencies = [
13
- "gaard-core==0.2.17",
14
- "gaard-connectors==0.2.17",
15
- "gaard-llm==0.2.17",
16
- "gaard-plugin-api>=0.2.17,<0.3.0",
13
+ "gaard-core==0.2.20",
14
+ "gaard-connectors==0.2.20",
15
+ "gaard-llm==0.2.20",
16
+ "gaard-plugin-api>=0.2.20,<0.3.0",
17
17
  "fastapi>=0.111.0",
18
18
  "uvicorn[standard]>=0.30.0",
19
19
  "pydantic>=2.7.0",
@@ -252,6 +252,19 @@ def seed_prompts(session: Session) -> None:
252
252
  continue
253
253
 
254
254
  if existing.updated_by != "system":
255
+ if existing.prompt_key == "sql_generation":
256
+ # Replace only the shipped LIMIT rules, preserving administrator customizations.
257
+ updated_prompt = existing.system_prompt.replace(
258
+ "Add LIMIT {max_rows} when the query may return many rows.",
259
+ "{row_limit_instruction}",
260
+ ).replace(
261
+ "Do not add LIMIT to pure aggregate queries that return a single row, "
262
+ "unless it is already useful for the dialect or safety.",
263
+ "Do not add a row limit to pure aggregate queries that return a single row.",
264
+ )
265
+ if updated_prompt != existing.system_prompt:
266
+ existing.system_prompt = updated_prompt
267
+ existing.version += 1
255
268
  continue
256
269
 
257
270
  changed = any(
@@ -1,3 +1,10 @@
1
+ from gaard_core.prompt_compiler.conversation_context_prompt import (
2
+ CONTEXT_DECISION_SYSTEM_PROMPT,
3
+ CONTEXT_DECISION_USER_PROMPT,
4
+ CONTEXT_SUMMARY_SYSTEM_PROMPT,
5
+ CONTEXT_SUMMARY_USER_PROMPT,
6
+ )
7
+
1
8
  DEFAULT_SQL_GENERATION_SYSTEM_PROMPT = """You are an expert data analyst and SQL specialist.
2
9
 
3
10
  Your task is to generate exactly one valid SQL SELECT query based on:
@@ -28,8 +35,8 @@ Query construction rules:
28
35
  3. If the user asks for both a total and a breakdown, prefer one SELECT statement that returns grouped rows or conditional aggregate columns.
29
36
  4. Do not solve one user question by generating multiple separate SELECT statements.
30
37
  5. Prefer explicit column names over SELECT *.
31
- 6. Add LIMIT {max_rows} when the query may return many rows.
32
- 7. Do not add LIMIT to pure aggregate queries that return a single row, unless it is already useful for the dialect or safety.
38
+ 6. {row_limit_instruction}
39
+ 7. Do not add a row limit to pure aggregate queries that return a single row.
33
40
  8. Use clear aliases for computed expressions.
34
41
  9. If the question is ambiguous, choose the most likely interpretation based on the schema, column names, descriptions and data rules.
35
42
 
@@ -86,74 +93,8 @@ Return one JSON object with:
86
93
  - reason: short explanation
87
94
  """
88
95
 
89
- DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_SYSTEM_PROMPT = """You are GAARD Conversation Context Classification.
90
-
91
- Your task is to decide whether the current user data question (turn t) is a
92
- logical continuation of the recent conversation turns (t-2 and t-1).
93
-
94
- Use the previous question-answer pairs as conversation evidence. Do not classify
95
- by rigid prefix or keyword rules. Decide semantically whether turn t depends on,
96
- compares with, narrows, broadens, or otherwise continues the immediately
97
- preceding analytical thread.
98
-
99
- Allowed decisions:
100
- - new_topic: answer "no" to logical continuation. The question starts a new analytical thread.
101
- - follow_up: answer "yes" to logical continuation. The question continues the
102
- recent thread and can be executed safely.
103
- - ambiguous: the question appears to continue the thread, but required entities,
104
- filters, date ranges, or datasource scope cannot be inferred safely.
105
-
106
- Decision rules:
107
- 1. First answer the yes/no question: is turn t a logical continuation of t-1/t-2?
108
- 2. A question can be a logical continuation even when it is already
109
- self-contained. In that case use follow_up, set
110
- current_question_is_standalone to true, and set standalone_question to the
111
- current question.
112
- 3. If the answer is no, use new_topic and set standalone_question to the current question.
113
- 4. If the answer is yes and the current question is elliptical, rewrite it as a
114
- standalone data question using t-1/t-2.
115
- 5. Use ambiguous only when the answer is yes but the continuation cannot be
116
- rewritten or executed safely without asking the user.
117
- 6. Treat detail/projection requests about the previous result as follow_up when
118
- the previous turn defines the result set. If the previous question counted,
119
- grouped, or filtered records and the user now asks for descriptions, names,
120
- statuses, fields, details, or values for those same records, rewrite by
121
- preserving the previous filters/date range/datasource and changing only the
122
- returned fields.
123
- 7. Do not mark a projection/detail follow-up ambiguous merely because the
124
- previous answer did not expose row ids. The previous standalone question and
125
- SQL are enough context for the next SQL generation step.
126
- 8. Never include rows or sensitive data in the standalone question.
127
-
128
- Output rules:
129
- - Return only a JSON object.
130
- - Do not include markdown.
131
- - Do not include reasoning outside the JSON.
132
- - Do not include <think> blocks.
133
- - Use exactly this JSON shape:
134
- {
135
- "is_continuation": false,
136
- "decision": "new_topic",
137
- "current_question_is_standalone": true,
138
- "confidence": 0.0,
139
- "standalone_question": "rewritten or current question",
140
- "reason": "short reason"
141
- }
142
- """
143
-
144
- DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_USER_PROMPT = """Decide whether turn t is a logical continuation of turns t-2 and t-1.
145
-
146
- Input JSON:
147
- {payload}
148
-
149
- Return one JSON object with:
150
- - is_continuation: boolean yes/no answer to the logical-continuation question
151
- - decision: one of new_topic, follow_up, ambiguous
152
- - current_question_is_standalone: boolean
153
- - confidence: number from 0 to 1
154
- - standalone_question: required for follow_up and new_topic; empty only for ambiguous
155
- - reason: short explanation
156
- """
96
+ DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_SYSTEM_PROMPT = CONTEXT_DECISION_SYSTEM_PROMPT
97
+ DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_USER_PROMPT = CONTEXT_DECISION_USER_PROMPT
157
98
 
158
99
  DEFAULT_RESULT_INTERPRETATION_SYSTEM_PROMPT = """You are GAARD Data Result Interpreter.
159
100
 
@@ -295,11 +236,18 @@ DEFAULT_PROMPTS = [
295
236
  "name": "Conversation context classification",
296
237
  "description": (
297
238
  "Decides whether the current question is a logical continuation "
298
- "of recent conversation turns."
239
+ "of the full context since the last new topic."
299
240
  ),
300
241
  "system_prompt": DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_SYSTEM_PROMPT,
301
242
  "user_prompt_template": DEFAULT_CONVERSATION_CONTEXT_CLASSIFICATION_USER_PROMPT,
302
243
  },
244
+ {
245
+ "prompt_key": "conversation_context_summary",
246
+ "name": "Conversation context summary",
247
+ "description": "Compresses the current context and follow-up into one standalone sentence.",
248
+ "system_prompt": CONTEXT_SUMMARY_SYSTEM_PROMPT,
249
+ "user_prompt_template": CONTEXT_SUMMARY_USER_PROMPT,
250
+ },
303
251
  {
304
252
  "prompt_key": "result_interpretation",
305
253
  "name": "Result interpretation",
@@ -2,10 +2,15 @@ from typing import Any
2
2
 
3
3
  from gaard_core.errors import ConfigurationError
4
4
  from gaard_core.json_utils import json_dumps
5
+ from gaard_core.prompt_compiler.conversation_context_prompt import (
6
+ CONTEXT_DECISION_SYSTEM_PROMPT,
7
+ CONTEXT_SUMMARY_SYSTEM_PROMPT,
8
+ conversation_context_payload,
9
+ )
5
10
  from gaard_core.prompt_compiler.models import CompiledPrompt, SqlGenerationPromptRequest
6
11
  from gaard_core.prompt_compiler.schema_formatter import SchemaPromptFormatter
12
+ from gaard_core.prompt_compiler.sql_generation_prompt import sql_row_limit_instruction
7
13
  from gaard_core.query_pipeline.models import (
8
- ConversationContextDecision,
9
14
  QueryRequest,
10
15
  QueryResult,
11
16
  )
@@ -29,12 +34,14 @@ class MetadataSqlGenerationPromptCompiler:
29
34
  system_prompt = self.prompt_template.system_prompt.format(
30
35
  dialect=request.dialect,
31
36
  max_rows=request.max_rows,
37
+ row_limit_instruction=sql_row_limit_instruction(request.dialect, request.max_rows),
32
38
  )
33
39
  user_prompt = self.prompt_template.user_prompt_template.format(
34
40
  schema=formatted_schema,
35
41
  question=request.question,
36
42
  dialect=request.dialect,
37
43
  max_rows=request.max_rows,
44
+ row_limit_instruction=sql_row_limit_instruction(request.dialect, request.max_rows),
38
45
  )
39
46
 
40
47
  return CompiledPrompt(
@@ -100,52 +107,36 @@ class MetadataConversationContextPromptCompiler:
100
107
  request: QueryRequest,
101
108
  conversation_context: dict[str, Any],
102
109
  ) -> CompiledPrompt:
103
- recent_turns = self._recent_turns(conversation_context)
104
- payload = {
105
- "turn_t_minus_2": recent_turns[0] if len(recent_turns) == 2 else {},
106
- "turn_t_minus_1": recent_turns[-1] if recent_turns else {},
107
- "turn_t": {
108
- "question": request.question,
109
- "datasource_id": request.datasource_id,
110
- "datasource_ids": request.datasource_ids,
111
- },
112
- }
113
- payload_json = json_dumps(payload, ensure_ascii=False, indent=2)
114
-
110
+ payload_json = json_dumps(
111
+ conversation_context_payload(request, conversation_context),
112
+ ensure_ascii=False,
113
+ indent=2,
114
+ )
115
+ is_summary = self.prompt_template.prompt_key == "conversation_context_summary"
116
+ contract = CONTEXT_SUMMARY_SYSTEM_PROMPT if is_summary else CONTEXT_DECISION_SYSTEM_PROMPT
117
+ user_prompt = self.prompt_template.user_prompt_template.format(
118
+ payload=payload_json,
119
+ question=request.question,
120
+ datasource_id=request.datasource_id,
121
+ datasource_ids=json_dumps(request.datasource_ids, ensure_ascii=False),
122
+ )
123
+ if payload_json not in user_prompt:
124
+ user_prompt += "\n\nComplete current input:\n" + payload_json
115
125
  return CompiledPrompt(
116
- system_prompt=self.prompt_template.system_prompt,
117
- user_prompt=self.prompt_template.user_prompt_template.format(
118
- payload=payload_json,
119
- question=request.question,
120
- datasource_id=request.datasource_id,
121
- datasource_ids=json_dumps(request.datasource_ids, ensure_ascii=False),
126
+ # The current contract also applies to customized prompts stored before this upgrade.
127
+ system_prompt=(
128
+ self.prompt_template.system_prompt
129
+ if self.prompt_template.system_prompt == contract
130
+ else self.prompt_template.system_prompt + "\n\nCurrent task contract:\n" + contract
122
131
  ),
132
+ user_prompt=user_prompt,
123
133
  metadata={
124
- "allowed_decisions": [item.value for item in ConversationContextDecision],
125
- "decision_task": "logical_continuation_yes_no",
134
+ "task": "conversation_context_summary" if is_summary else "conversation_context_decision",
126
135
  "prompt_key": self.prompt_template.prompt_key,
127
136
  "prompt_version": self.prompt_template.version,
128
137
  },
129
138
  )
130
139
 
131
- def _recent_turns(self, conversation_context: dict[str, Any]) -> list[dict[str, Any]]:
132
- turns = [
133
- turn for turn in conversation_context.get("turns", []) if isinstance(turn, dict)
134
- ][-2:]
135
- labels = ["t-2", "t-1"] if len(turns) == 2 else ["t-1"]
136
- return [
137
- {
138
- "label": label,
139
- "question": str(turn.get("question") or ""),
140
- "standalone_question": str(turn.get("standalone_question") or ""),
141
- "answer": str(turn.get("answer") or ""),
142
- "sql": str(turn.get("sql") or ""),
143
- "context_decision": str(turn.get("context_decision") or ""),
144
- "context_reason": str(turn.get("context_reason") or ""),
145
- }
146
- for label, turn in zip(labels, turns, strict=False)
147
- ]
148
-
149
140
 
150
141
  class MetadataResultInterpretationPromptCompiler:
151
142
  def __init__(self, prompt_template: PromptTemplate) -> None:
@@ -281,6 +272,15 @@ def get_conversation_context_prompt_compiler() -> (
281
272
  return MetadataConversationContextPromptCompiler(prompt_template=prompt_template)
282
273
 
283
274
 
275
+ def get_conversation_context_summary_prompt_compiler() -> (
276
+ MetadataConversationContextPromptCompiler | None
277
+ ):
278
+ prompt_template = get_active_prompt_template_safe("conversation_context_summary")
279
+ if prompt_template is None:
280
+ return None
281
+ return MetadataConversationContextPromptCompiler(prompt_template=prompt_template)
282
+
283
+
284
284
  def get_result_interpretation_prompt_compiler() -> (
285
285
  MetadataResultInterpretationPromptCompiler | None
286
286
  ):
@@ -1747,6 +1747,14 @@ def upsert_llm_business_logic_suggestion(
1747
1747
  )
1748
1748
  )
1749
1749
 
1750
+ if existing is None:
1751
+ existing = session.scalar(
1752
+ select(BusinessLogicSuggestion).where(
1753
+ BusinessLogicSuggestion.connector_id == connector.id,
1754
+ BusinessLogicSuggestion.rule_text == lesson.rule_text,
1755
+ )
1756
+ )
1757
+
1750
1758
  if existing is None:
1751
1759
  existing = BusinessLogicSuggestion(
1752
1760
  connector_id=connector.id,
@@ -1769,6 +1777,10 @@ def upsert_llm_business_logic_suggestion(
1769
1777
  return existing
1770
1778
 
1771
1779
  existing.source_audit_id = audit_log.id
1780
+ # Re-observing an error must not revoke approval or overwrite reviewed content.
1781
+ if existing.enabled:
1782
+ return existing
1783
+
1772
1784
  existing.status = BUSINESS_LOGIC_STATUS_PENDING
1773
1785
  existing.safety = BUSINESS_LOGIC_SAFETY_REVIEW
1774
1786
  existing.enabled = False
@@ -1872,9 +1884,12 @@ def record_business_logic_learning_suggestion(
1872
1884
  metadata["failed_identifier"] = lesson.failed_identifier
1873
1885
  metadata["repaired_identifier"] = lesson.repaired_identifier
1874
1886
  metadata["business_logic_learning"] = {
1875
- "status": "pending_approval",
1887
+ "status": BUSINESS_LOGIC_STATUS_ACTIVE if suggestion.enabled else "pending_approval",
1876
1888
  "suggestion_id": suggestion.id,
1877
1889
  "message": (
1890
+ "This error matches an already approved business logic rule. "
1891
+ "The rule remains active."
1892
+ if suggestion.enabled else
1878
1893
  "Nauczyłem się propozycji rozwiązania tego błędu, ale musisz ją "
1879
1894
  "zatwierdzić w Sugestiach logiki biznesowej."
1880
1895
  ),
@@ -12,7 +12,9 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status
12
12
  from fastapi.responses import StreamingResponse
13
13
  from gaard_core.llm_output import remove_thinking_blocks
14
14
  from gaard_core.query_pipeline.models import (
15
+ ContextMode,
15
16
  ConversationContextClassification,
17
+ ConversationContextDecision,
16
18
  OutputClassification,
17
19
  QueryRequest,
18
20
  QueryResponse,
@@ -69,7 +71,7 @@ from gaard_api.auth_dependencies import (
69
71
  get_current_enterprise_api_user,
70
72
  identity_id_for_principal,
71
73
  )
72
- from gaard_api.conversations import load_conversation_for_owner
74
+ from gaard_api.conversations import fail_conversation_turn, record_conversation_turn
73
75
  from gaard_api.query_hooks import (
74
76
  DatasourceContext,
75
77
  DatasourceContexts,
@@ -1542,6 +1544,23 @@ def run_analysis_loop(
1542
1544
  decision.visible_question,
1543
1545
  )
1544
1546
  save_analysis_context(session_id, context, "waiting_for_user")
1547
+ if conversation is not None and context_classification is not None:
1548
+ record_conversation_turn(
1549
+ conversation,
1550
+ mode="analysis",
1551
+ original_question=visible_request.question,
1552
+ standalone_question=request.question,
1553
+ answer=user_question,
1554
+ sql="",
1555
+ metadata={
1556
+ "datasource_id": request.datasource_id,
1557
+ "datasource_ids": request.datasource_ids,
1558
+ "output_classification": OutputClassification.TECHNICAL_DATA.value,
1559
+ },
1560
+ context_classification=context_classification,
1561
+ status="waiting_for_user",
1562
+ analysis_session_id=session_id,
1563
+ )
1545
1564
  yield stream_event(
1546
1565
  session_id,
1547
1566
  "user_question",
@@ -1729,6 +1748,7 @@ def run_analysis_loop(
1729
1748
  )
1730
1749
  yield stream_event(session_id, "final", response.model_dump(mode="json"))
1731
1750
  except Exception as exc:
1751
+ fail_conversation_turn(conversation, context_classification, exc)
1732
1752
  save_analysis_context(session_id, context, "failed")
1733
1753
  yield stream_event(
1734
1754
  session_id,
@@ -1778,13 +1798,14 @@ def analysis_stream(
1778
1798
  conversation, context_classification, analysis_request = resolve_request_conversation(
1779
1799
  effective_request,
1780
1800
  conversation_principal(_user),
1801
+ mode="analysis",
1781
1802
  )
1782
1803
  record = create_analysis_session_record(
1783
1804
  effective_request,
1784
1805
  owner_user_id=identity_id_for_principal(_user),
1785
1806
  )
1786
1807
  if conversation is not None:
1787
- standalone_question = analysis_request.question if analysis_request is not None else ""
1808
+ standalone_question = analysis_request.question
1788
1809
  attach_conversation_to_analysis_context(
1789
1810
  record.session_id,
1790
1811
  conversation.conversation_id,
@@ -1793,55 +1814,10 @@ def analysis_stream(
1793
1814
  )
1794
1815
  record = load_analysis_session_record(record.session_id) or record
1795
1816
 
1796
- if conversation is not None and analysis_request is None:
1797
- response = QueryResponse(
1798
- question=effective_request.question,
1799
- answer=(
1800
- "Potrzebuję doprecyzowania, czy to pytanie jest kontynuacją poprzedniego "
1801
- "wątku i jak mam je rozumieć."
1802
- ),
1803
- sql="",
1804
- rows=[],
1805
- metadata={
1806
- **final_metadata(record.session_id, "waiting_for_user", 0),
1807
- "output_classification": OutputClassification.UNKNOWN.value,
1808
- "blocked": True,
1809
- "blocked_reason": "conversation.ambiguous_context",
1810
- },
1811
- )
1812
- response = finalize_analysis_response(
1813
- response,
1814
- conversation=conversation,
1815
- context_classification=context_classification,
1816
- original_request=effective_request,
1817
- effective_request=effective_request,
1818
- )
1819
-
1820
- def ambiguous_stream() -> Iterator[str]:
1821
- yield stream_event(
1822
- record.session_id,
1823
- "session_started",
1824
- {
1825
- **serialize_analysis_session(record),
1826
- "conversation_id": conversation.conversation_id,
1827
- },
1828
- )
1829
- save_analysis_context(
1830
- record.session_id,
1831
- json_object(record.context_json),
1832
- "waiting_for_user",
1833
- )
1834
- yield stream_event(record.session_id, "final", response.model_dump(mode="json"))
1835
-
1836
- return StreamingResponse(
1837
- ambiguous_stream(),
1838
- media_type="application/x-ndjson",
1839
- )
1840
-
1841
1817
  return StreamingResponse(
1842
1818
  start_stream_for_record(
1843
1819
  record,
1844
- analysis_request or effective_request,
1820
+ analysis_request,
1845
1821
  datasource_context,
1846
1822
  conversation=conversation,
1847
1823
  context_classification=context_classification if conversation is not None else None,
@@ -1869,51 +1845,55 @@ def analysis_message_stream(
1869
1845
  )
1870
1846
 
1871
1847
  context = json_object(record.context_json)
1872
- conversation = None
1873
- context_classification = None
1874
1848
  conversation_id = str(context.get("conversation_id") or "")
1875
- if conversation_id:
1876
- conversation = load_conversation_for_owner(
1877
- conversation_id,
1878
- conversation_principal(_user),
1879
- )
1880
- if conversation is None:
1881
- raise HTTPException(
1882
- status_code=status.HTTP_403_FORBIDDEN,
1883
- detail="Conversation belongs to another user.",
1884
- )
1885
- raw_classification = context.get("conversation_context") or {}
1886
- if isinstance(raw_classification, dict):
1887
- context_classification = ConversationContextClassification.model_validate(
1888
- raw_classification
1889
- )
1890
-
1891
- context.setdefault("messages", []).append(
1892
- {
1893
- "role": "user",
1894
- "content": request.message,
1895
- "occurred_at": utc_iso(),
1896
- }
1897
- )
1898
- save_analysis_context(session_id, context, "running")
1899
1849
  query_request = QueryRequest(
1900
- question=str(context.get("conversation_standalone_question") or record.question),
1850
+ question=request.message,
1901
1851
  datasource_id=record.datasource_id,
1902
1852
  user_id=record.user_id,
1903
1853
  conversation_id=conversation_id or None,
1854
+ context_mode=ContextMode.AUTO if conversation_id else ContextMode.OFF,
1904
1855
  )
1905
1856
  effective_request, datasource_context = effective_query_request(query_request, _user)
1906
- refreshed_record = load_analysis_session_record(session_id) or record
1857
+ conversation, classification, analysis_request = resolve_request_conversation(
1858
+ effective_request, conversation_principal(_user), mode="analysis"
1859
+ )
1860
+ resumed = True
1861
+ if (
1862
+ conversation is not None
1863
+ and classification.decision == ConversationContextDecision.NEW_TOPIC
1864
+ ):
1865
+ # A new topic must not inherit the old analysis observations or working findings.
1866
+ record = create_analysis_session_record(
1867
+ effective_request, owner_user_id=identity_id_for_principal(_user)
1868
+ )
1869
+ session_id = record.session_id
1870
+ context = json_object(record.context_json)
1871
+ resumed = False
1907
1872
 
1873
+ if resumed:
1874
+ context.setdefault("messages", []).append(
1875
+ {
1876
+ "role": "user",
1877
+ "content": request.message,
1878
+ "occurred_at": utc_iso(),
1879
+ }
1880
+ )
1881
+ context["original_question"] = request.message
1882
+ save_analysis_context(session_id, context, "running")
1883
+ if conversation is not None:
1884
+ attach_conversation_to_analysis_context(
1885
+ session_id, conversation.conversation_id, classification, analysis_request.question
1886
+ )
1887
+ refreshed_record = load_analysis_session_record(session_id) or record
1908
1888
  return StreamingResponse(
1909
1889
  start_stream_for_record(
1910
1890
  refreshed_record,
1911
- effective_request,
1891
+ analysis_request,
1912
1892
  datasource_context,
1913
- resumed=True,
1893
+ resumed=resumed,
1914
1894
  conversation=conversation,
1915
- context_classification=context_classification,
1916
- original_request=query_request.model_copy(update={"question": record.question}),
1895
+ context_classification=classification if conversation is not None else None,
1896
+ original_request=effective_request,
1917
1897
  enterprise_access=_user.user.enterprise_access,
1918
1898
  ),
1919
1899
  media_type="application/x-ndjson",