agent-semantic-layer 0.0.1__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.
@@ -0,0 +1,197 @@
1
+ """The LLM-facing projection of a Semantic View (the "B-class" context).
2
+
3
+ A :class:`SemanticView` mixes two kinds of information: physical detail the
4
+ compiler needs (``expr``, ``base_table``, ``primary_key``, ``access_modifier``)
5
+ and business context the LLM needs (names, descriptions, synonyms, enum values,
6
+ ``custom_instructions``, onboarding questions).
7
+
8
+ This module carves out *only* the second kind into a :class:`SemanticContext`,
9
+ so the LLM never sees physical exprs, base tables, or ``private_access`` items.
10
+ The guiding principle: **if it does not help the LLM decide how to call the
11
+ query tool, do not expose it.**
12
+
13
+ Two levels of disclosure (progressive, like Agent Skills):
14
+
15
+ * :meth:`SemanticContext.summary` — the lightweight intro that goes into the
16
+ system prompt up front: view name, description, custom instructions, and the
17
+ onboarding questions.
18
+ * :meth:`SemanticContext.describe` — the full context (tables, items, synonyms,
19
+ enums, relationships) the LLM pulls on demand when the summary is not enough.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import TYPE_CHECKING
25
+
26
+ from pydantic import BaseModel, Field
27
+
28
+ if TYPE_CHECKING: # avoid a runtime import cycle with model.py
29
+ from .model import SemanticView
30
+
31
+
32
+ # ── Context item shapes (no expr, no access_modifier) ─────────────────
33
+
34
+
35
+ class ContextItem(BaseModel):
36
+ """A single dimension / fact / metric as the LLM sees it."""
37
+
38
+ name: str
39
+ kind: str # "dimension" | "fact" | "metric"
40
+ description: str | None = None
41
+ synonyms: list[str] = Field(default_factory=list)
42
+ data_type: str | None = None
43
+ # For low-cardinality dimensions we surface the label hint so the LLM knows
44
+ # it is a good filter target. Actual enum *values* are not stored in the
45
+ # model, so we only carry the is_enum flag.
46
+ is_enum: bool = False
47
+ is_filter_hint: bool = False
48
+
49
+
50
+ class ContextTable(BaseModel):
51
+ """A logical table as the LLM sees it: business info only."""
52
+
53
+ name: str
54
+ description: str | None = None
55
+ dimensions: list[ContextItem] = Field(default_factory=list)
56
+ facts: list[ContextItem] = Field(default_factory=list)
57
+ metrics: list[ContextItem] = Field(default_factory=list)
58
+
59
+
60
+ class ContextRelationship(BaseModel):
61
+ """A join the LLM should know about (so it can select across tables)."""
62
+
63
+ name: str
64
+ left_table: str
65
+ right_table: str
66
+
67
+
68
+ class ContextVerifiedQuery(BaseModel):
69
+ name: str
70
+ question: str
71
+
72
+
73
+ class SemanticContext(BaseModel):
74
+ """Everything the LLM is allowed to know about a Semantic View.
75
+
76
+ Rendering to prompt text lives in ``prompt.py``; this type is the structured
77
+ intermediate so the projection stays testable and free of formatting.
78
+ """
79
+
80
+ name: str
81
+ description: str | None = None
82
+ custom_instructions: str | None = None
83
+ tables: list[ContextTable] = Field(default_factory=list)
84
+ metrics: list[ContextItem] = Field(default_factory=list) # view-level derived
85
+ relationships: list[ContextRelationship] = Field(default_factory=list)
86
+ verified_queries: list[ContextVerifiedQuery] = Field(default_factory=list)
87
+
88
+ def summary(self) -> SemanticContextSummary:
89
+ """The lightweight intro (name/description/instructions/onboarding)."""
90
+ return SemanticContextSummary(
91
+ name=self.name,
92
+ description=self.description,
93
+ custom_instructions=self.custom_instructions,
94
+ verified_queries=self.verified_queries,
95
+ )
96
+
97
+
98
+ class SemanticContextSummary(BaseModel):
99
+ """The up-front slice injected into the system prompt.
100
+
101
+ Deliberately small: enough for the LLM to know the view exists and roughly
102
+ what it answers, plus example questions. Full detail is fetched on demand.
103
+ """
104
+
105
+ name: str
106
+ description: str | None = None
107
+ custom_instructions: str | None = None
108
+ verified_queries: list[ContextVerifiedQuery] = Field(default_factory=list)
109
+
110
+
111
+ # ── Projection ────────────────────────────────────────────────────────
112
+
113
+
114
+ def build_semantic_context(view: SemanticView) -> SemanticContext:
115
+ """Project a :class:`SemanticView` down to its LLM-safe context.
116
+
117
+ Drops every ``expr`` and every ``private_access`` fact/metric. Time
118
+ dimensions are folded in with regular dimensions (the LLM treats them the
119
+ same when selecting/filtering).
120
+ """
121
+ tables: list[ContextTable] = []
122
+ for t in view.tables:
123
+ dims = [_dim_item(d) for d in (*t.dimensions, *t.time_dimensions)]
124
+ facts = [
125
+ _fact_item(f) for f in t.facts if f.access_modifier != "private_access"
126
+ ]
127
+ metrics = [
128
+ _metric_item(m) for m in t.metrics if m.access_modifier != "private_access"
129
+ ]
130
+ tables.append(
131
+ ContextTable(
132
+ name=t.name,
133
+ description=t.description,
134
+ dimensions=dims,
135
+ facts=facts,
136
+ metrics=metrics,
137
+ )
138
+ )
139
+
140
+ view_metrics = [
141
+ _metric_item(m) for m in view.metrics if m.access_modifier != "private_access"
142
+ ]
143
+
144
+ relationships = [
145
+ ContextRelationship(
146
+ name=r.name, left_table=r.left_table, right_table=r.right_table
147
+ )
148
+ for r in view.relationships
149
+ ]
150
+
151
+ verified = [
152
+ ContextVerifiedQuery(name=v.name, question=v.question)
153
+ for v in view.verified_queries
154
+ ]
155
+
156
+ return SemanticContext(
157
+ name=view.name,
158
+ description=view.description,
159
+ custom_instructions=view.custom_instructions,
160
+ tables=tables,
161
+ metrics=view_metrics,
162
+ relationships=relationships,
163
+ verified_queries=verified,
164
+ )
165
+
166
+
167
+ def _dim_item(d) -> ContextItem:
168
+ return ContextItem(
169
+ name=d.name,
170
+ kind="dimension",
171
+ description=d.description,
172
+ synonyms=list(d.synonyms),
173
+ data_type=d.data_type,
174
+ is_enum=bool(getattr(d, "is_enum", False)),
175
+ is_filter_hint="filter" in getattr(d, "labels", []),
176
+ )
177
+
178
+
179
+ def _fact_item(f) -> ContextItem:
180
+ return ContextItem(
181
+ name=f.name,
182
+ kind="fact",
183
+ description=f.description,
184
+ synonyms=list(f.synonyms),
185
+ data_type=f.data_type,
186
+ is_filter_hint="filter" in getattr(f, "labels", []),
187
+ )
188
+
189
+
190
+ def _metric_item(m) -> ContextItem:
191
+ return ContextItem(
192
+ name=m.name,
193
+ kind="metric",
194
+ description=m.description,
195
+ synonyms=list(m.synonyms),
196
+ data_type=m.data_type,
197
+ )
@@ -0,0 +1,5 @@
1
+ """Errors shared by query execution components."""
2
+
3
+
4
+ class CompileError(Exception):
5
+ """Raised when a structured query cannot be compiled against a semantic view."""
@@ -0,0 +1,77 @@
1
+ """Load a user-authored Semantic View YAML into a :class:`SemanticView`.
2
+
3
+ Loading is intentionally thin: parse YAML to a dict, then let Pydantic build and
4
+ validate the :class:`SemanticView`. No JSON-Schema step — Pydantic is the single
5
+ source of structural truth here.
6
+
7
+ Fields the compiler and the LLM-context projection do not use are ignored rather
8
+ than rejected, so a richer author-side YAML still
9
+ loads. Fields we *do* model are validated strictly by the Pydantic types.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+ from pydantic import ValidationError
19
+
20
+ from .model import SemanticView
21
+
22
+
23
+ class SemanticViewLoadError(Exception):
24
+ """Raised when a Semantic View YAML cannot be parsed or validated."""
25
+
26
+
27
+ def load_semantic_view(source: str | Path) -> SemanticView:
28
+ """Load and validate a Semantic View from a YAML file path.
29
+
30
+ Parameters
31
+ ----------
32
+ source:
33
+ Path to a ``*.yml`` / ``*.yaml`` file authored per SLQP Part II.
34
+
35
+ Returns
36
+ -------
37
+ SemanticView
38
+ The validated in-memory view, ready for the compiler and for
39
+ :meth:`SemanticView.context`.
40
+
41
+ Raises
42
+ ------
43
+ SemanticViewLoadError
44
+ If the file is missing, not valid YAML, or does not match the schema.
45
+ """
46
+ path = Path(source)
47
+ try:
48
+ text = path.read_text(encoding="utf-8")
49
+ except OSError as exc:
50
+ raise SemanticViewLoadError(
51
+ f"cannot read semantic view '{path}': {exc}"
52
+ ) from exc
53
+ return load_semantic_view_from_string(text, origin=str(path))
54
+
55
+
56
+ def load_semantic_view_from_string(
57
+ text: str, *, origin: str = "<string>"
58
+ ) -> SemanticView:
59
+ """Load and validate a Semantic View from raw YAML text.
60
+
61
+ Kept separate from :func:`load_semantic_view` so callers that already hold
62
+ the YAML (tests, config stores, HTTP payloads) do not need a file on disk.
63
+ """
64
+ try:
65
+ data: Any = yaml.safe_load(text)
66
+ except yaml.YAMLError as exc:
67
+ raise SemanticViewLoadError(f"invalid YAML in {origin}: {exc}") from exc
68
+
69
+ if not isinstance(data, dict):
70
+ raise SemanticViewLoadError(
71
+ f"{origin}: expected a mapping at the top level, got {type(data).__name__}"
72
+ )
73
+
74
+ try:
75
+ return SemanticView.model_validate(data)
76
+ except ValidationError as exc:
77
+ raise SemanticViewLoadError(f"{origin}: {exc}") from exc
@@ -0,0 +1,347 @@
1
+ """Semantic Model types (SLQP Part II).
2
+
3
+ These Pydantic models mirror the human-authored semantic-model YAML.
4
+ They are the *input contract* the engine
5
+ consumes: loading and validation happen elsewhere, this module only defines the
6
+ shape and offers a few resolution helpers the compiler needs.
7
+
8
+ Nothing here writes SQL. The physical ``expr`` strings and ``base_table``
9
+ bindings live here so the compiler can turn a logical query into concrete SQL.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING, Literal
15
+
16
+ from pydantic import BaseModel, Field, model_validator
17
+
18
+ from .query import SemanticQuery
19
+
20
+ if TYPE_CHECKING:
21
+ from .context import SemanticContext
22
+
23
+ DataType = Literal["string", "number", "integer", "date", "timestamp", "boolean"]
24
+ AccessModifier = Literal["public_access", "private_access"]
25
+
26
+ # ── Item kinds ────────────────────────────────────────────────────────
27
+
28
+
29
+ class Dimension(BaseModel):
30
+ """Categorical / descriptive attribute (row-level, non-aggregate)."""
31
+
32
+ name: str
33
+ expr: str = Field(description="Physical, row-level SQL expression.")
34
+ description: str | None = None
35
+ synonyms: list[str] = Field(default_factory=list)
36
+ data_type: DataType | None = None
37
+ is_enum: bool = False
38
+ labels: list[str] = Field(default_factory=list)
39
+
40
+
41
+ class Fact(BaseModel):
42
+ """Raw row-level numeric attribute; a building block for metrics."""
43
+
44
+ name: str
45
+ expr: str = Field(description="Physical, row-level SQL expression.")
46
+ description: str | None = None
47
+ synonyms: list[str] = Field(default_factory=list)
48
+ data_type: DataType | None = None
49
+ access_modifier: AccessModifier = "public_access"
50
+ labels: list[str] = Field(default_factory=list)
51
+
52
+
53
+ class Metric(BaseModel):
54
+ """Aggregation / KPI scoped to a single logical table."""
55
+
56
+ name: str
57
+ expr: str = Field(description="Physical SQL expression that aggregates.")
58
+ description: str | None = None
59
+ synonyms: list[str] = Field(default_factory=list)
60
+ data_type: DataType | None = None
61
+ access_modifier: AccessModifier = "public_access"
62
+ using_relationships: list[str] = Field(default_factory=list)
63
+
64
+
65
+ class NamedFilter(BaseModel):
66
+ """A reusable, row-level boolean predicate fragment."""
67
+
68
+ name: str
69
+ expr: str
70
+ description: str | None = None
71
+ synonyms: list[str] = Field(default_factory=list)
72
+
73
+
74
+ # ── Physical binding ─────────────────────────────────────────────────
75
+
76
+
77
+ class BaseTable(BaseModel):
78
+ """Physical binding: a fully-qualified table OR a SQL query definition."""
79
+
80
+ database: str | None = Field(default=None, min_length=1)
81
+ schema_: str | None = Field(default=None, alias="schema", min_length=1)
82
+ table: str | None = Field(default=None, min_length=1)
83
+ definition: str | None = Field(
84
+ default=None,
85
+ min_length=1,
86
+ description="A SQL query used instead of database/schema/table.",
87
+ )
88
+
89
+ model_config = {
90
+ "populate_by_name": True,
91
+ "json_schema_extra": {
92
+ "anyOf": [
93
+ {
94
+ "required": ["table"],
95
+ "properties": {
96
+ "table": {"type": "string", "minLength": 1},
97
+ "definition": {"type": "null"},
98
+ },
99
+ },
100
+ {
101
+ "required": ["definition"],
102
+ "properties": {
103
+ "definition": {"type": "string", "minLength": 1},
104
+ "database": {"type": "null"},
105
+ "schema": {"type": "null"},
106
+ "table": {"type": "null"},
107
+ },
108
+ },
109
+ ],
110
+ },
111
+ }
112
+
113
+ @model_validator(mode="after")
114
+ def validate_binding(self) -> BaseTable:
115
+ if self.definition is not None:
116
+ if any(
117
+ value is not None for value in (self.database, self.schema_, self.table)
118
+ ):
119
+ raise ValueError(
120
+ "definition cannot be combined with database, schema, or table"
121
+ )
122
+ elif self.table is None:
123
+ raise ValueError("base_table requires a table or definition")
124
+ return self
125
+
126
+ def is_query(self) -> bool:
127
+ return self.definition is not None
128
+
129
+ def qualified_name(self) -> str:
130
+ """Return ``DATABASE.SCHEMA.TABLE`` for a bound table.
131
+
132
+ Query-defined base tables have no qualified name; the compiler wraps
133
+ their ``definition`` in a subquery instead.
134
+ """
135
+ if self.is_query():
136
+ raise ValueError("base_table is query-defined; use definition instead")
137
+ parts = [p for p in (self.database, self.schema_, self.table) if p]
138
+ return ".".join(parts)
139
+
140
+
141
+ # ── Logical table ────────────────────────────────────────────────────
142
+
143
+
144
+ class KeySpec(BaseModel):
145
+ columns: list[str] = Field(min_length=1)
146
+
147
+
148
+ class LogicalTable(BaseModel):
149
+ """A business entity backed by a physical table/view."""
150
+
151
+ name: str
152
+ base_table: BaseTable
153
+ description: str | None = None
154
+ primary_key: KeySpec | None = None
155
+ unique_keys: list[KeySpec] = Field(default_factory=list)
156
+ dimensions: list[Dimension] = Field(default_factory=list)
157
+ time_dimensions: list[Dimension] = Field(default_factory=list)
158
+ facts: list[Fact] = Field(default_factory=list)
159
+ metrics: list[Metric] = Field(default_factory=list)
160
+ filters: list[NamedFilter] = Field(default_factory=list)
161
+
162
+ def all_dimensions(self) -> list[Dimension]:
163
+ """Dimensions plus time_dimensions (both are row-level attributes)."""
164
+ return [*self.dimensions, *self.time_dimensions]
165
+
166
+
167
+ # ── Relationships / variables / derived metrics ──────────────────────
168
+
169
+
170
+ class RelationshipColumn(BaseModel):
171
+ left_column: str
172
+ right_column: str
173
+ type: Literal["asof", "range"] | None = None
174
+ right_range: dict | None = None
175
+
176
+
177
+ class Relationship(BaseModel):
178
+ """A declared join between two logical tables."""
179
+
180
+ name: str
181
+ left_table: str
182
+ right_table: str
183
+ relationship_columns: list[RelationshipColumn] = Field(min_length=1)
184
+
185
+
186
+ class Variable(BaseModel):
187
+ name: str
188
+ data_type: DataType
189
+ default_value: str | None = None
190
+ description: str | None = None
191
+
192
+
193
+ class DerivedMetric(BaseModel):
194
+ """A view-level metric whose expr may reference items across tables."""
195
+
196
+ name: str
197
+ expr: str
198
+ description: str | None = None
199
+ synonyms: list[str] = Field(default_factory=list)
200
+ data_type: DataType | None = None
201
+ access_modifier: AccessModifier = "public_access"
202
+
203
+
204
+ # ── The model ────────────────────────────────────────────────────────
205
+
206
+
207
+ class ResolvedItem(BaseModel):
208
+ """The result of resolving a logical name against the model.
209
+
210
+ ``kind`` tells the compiler how to treat the ``expr`` (group vs aggregate),
211
+ and ``table`` is ``None`` for view-level derived metrics whose expr already
212
+ references items as ``table.item``.
213
+ """
214
+
215
+ kind: Literal["dimension", "fact", "metric", "derived_metric"]
216
+ name: str
217
+ expr: str
218
+ table: LogicalTable | None = None
219
+
220
+
221
+ class VerifiedQuery(BaseModel):
222
+ """A question -> verified example, used as an onboarding hint for the LLM.
223
+
224
+ Only the ``question`` is exposed to the LLM (as a "you can ask me things
225
+ like this" hint). The embedded ``semantic_query`` is intentionally *not*
226
+ surfaced: the query tool already advertises the ``SemanticQuery`` shape via
227
+ its input schema, so re-teaching it here would be redundant.
228
+ """
229
+
230
+ name: str
231
+ question: str
232
+ use_as_onboarding_question: bool = False
233
+ semantic_query: SemanticQuery | None = None
234
+ verified_at: int | None = None
235
+ verified_by: str | None = None
236
+
237
+
238
+ class SemanticView(BaseModel):
239
+ """The in-memory semantic view loaded from a user's YAML.
240
+
241
+ This is the full domain model (both the compile-facing physical info —
242
+ ``expr`` / ``base_table`` / relationships — and the LLM-facing context —
243
+ descriptions / synonyms / enum values). The compiler consumes the whole
244
+ view; the LLM only ever sees the projected :class:`SemanticContext`
245
+ (see :meth:`context`), which strips ``expr`` and ``private_access`` items.
246
+ """
247
+
248
+ name: str
249
+ tables: list[LogicalTable] = Field(min_length=1)
250
+ description: str | None = None
251
+ relationships: list[Relationship] = Field(default_factory=list)
252
+ variables: list[Variable] = Field(default_factory=list)
253
+ metrics: list[DerivedMetric] = Field(default_factory=list)
254
+ # Context-only fields (B-class): fed to the LLM via SemanticContext, never
255
+ # used by the compiler.
256
+ verified_queries: list[VerifiedQuery] = Field(default_factory=list)
257
+ custom_instructions: str | None = None
258
+
259
+ # -- context projection -------------------------------------------
260
+
261
+ def context(self) -> SemanticContext:
262
+ """Project the LLM-facing context (no ``expr``, no ``private_access``).
263
+
264
+ This is the single place that decides what the model is allowed to see.
265
+ Everything physical (``expr``, ``base_table``) and everything marked
266
+ ``private_access`` is dropped here so it can never leak into a prompt.
267
+ """
268
+ from .context import build_semantic_context
269
+
270
+ return build_semantic_context(self)
271
+
272
+ # -- lookups ------------------------------------------------------
273
+
274
+ def table(self, name: str) -> LogicalTable | None:
275
+ for t in self.tables:
276
+ if t.name == name:
277
+ return t
278
+ return None
279
+
280
+ def resolve(self, name: str) -> ResolvedItem | None:
281
+ """Resolve a (possibly qualified) logical ``name`` to a model item.
282
+
283
+ Accepts ``table.item`` (qualified) or ``item`` (unqualified). Loading and
284
+ validation are done upstream, so this returns ``None`` when the name is
285
+ missing or does not identify exactly one public item. ``private_access``
286
+ items are not resolvable from a query.
287
+ """
288
+ if "." in name:
289
+ table_name, item_name = name.split(".", 1)
290
+ table = self.table(table_name)
291
+ if table is None:
292
+ # Could be a view-level derived metric that happens to contain
293
+ # a dot? No — derived metrics are unqualified names. Miss.
294
+ return self._resolve_derived(name)
295
+ return self._resolve_in_table(table, item_name)
296
+
297
+ # Unqualified names must identify exactly one item across the view.
298
+ matches = self._resolve_derived_candidates(name)
299
+ for table in self.tables:
300
+ matches.extend(self._resolve_in_table_candidates(table, name))
301
+ return matches[0] if len(matches) == 1 else None
302
+
303
+ def _resolve_derived(self, name: str) -> ResolvedItem | None:
304
+ matches = self._resolve_derived_candidates(name)
305
+ return matches[0] if len(matches) == 1 else None
306
+
307
+ def _resolve_derived_candidates(self, name: str) -> list[ResolvedItem]:
308
+ return [
309
+ ResolvedItem(kind="derived_metric", name=m.name, expr=m.expr, table=None)
310
+ for m in self.metrics
311
+ if m.name == name and m.access_modifier != "private_access"
312
+ ]
313
+
314
+ @staticmethod
315
+ def _resolve_in_table(table: LogicalTable, item_name: str) -> ResolvedItem | None:
316
+ matches = SemanticView._resolve_in_table_candidates(table, item_name)
317
+ return matches[0] if len(matches) == 1 else None
318
+
319
+ @staticmethod
320
+ def _resolve_in_table_candidates(
321
+ table: LogicalTable, item_name: str
322
+ ) -> list[ResolvedItem]:
323
+ matches: list[ResolvedItem] = []
324
+ for d in table.all_dimensions():
325
+ if d.name == item_name:
326
+ matches.append(
327
+ ResolvedItem(
328
+ kind="dimension", name=d.name, expr=d.expr, table=table
329
+ )
330
+ )
331
+ for f in table.facts:
332
+ if f.name == item_name and f.access_modifier != "private_access":
333
+ matches.append(
334
+ ResolvedItem(kind="fact", name=f.name, expr=f.expr, table=table)
335
+ )
336
+ for m in table.metrics:
337
+ if m.name == item_name and m.access_modifier != "private_access":
338
+ matches.append(
339
+ ResolvedItem(kind="metric", name=m.name, expr=m.expr, table=table)
340
+ )
341
+ return matches
342
+
343
+ def named_filter(self, table: LogicalTable, name: str) -> NamedFilter | None:
344
+ for nf in table.filters:
345
+ if nf.name == name:
346
+ return nf
347
+ return None