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,153 @@
1
+ """Render a :class:`SemanticContext` into prompt text for the LLM.
2
+
3
+ Two renderers, matching the two disclosure levels:
4
+
5
+ * :func:`render_summary` — the short intro injected into the system prompt up
6
+ front (view name, description, custom instructions, onboarding questions),
7
+ plus a nudge to fetch full detail via the describe tool before querying.
8
+ * :func:`render_describe` — the full context returned by the describe tool:
9
+ tables with their dimensions / facts / metrics (names, descriptions,
10
+ synonyms, enum/filter hints), view-level metrics, and relationships.
11
+
12
+ All formatting lives here so :mod:`context` stays a pure data projection and the
13
+ middleware/tools stay logic-only.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from .context import ContextItem, SemanticContext
19
+
20
+ # Tool names referenced in the prompt copy. Kept here so the wording and the
21
+ # actual tool registrations (tools.py) share one source of truth.
22
+ DESCRIBE_TOOL_NAME = "describe_semantic_view"
23
+ QUERY_TOOL_NAME = "run_semantic_query"
24
+
25
+
26
+ def render_summary(context: SemanticContext) -> str:
27
+ """The up-front system-prompt block describing one available view.
28
+
29
+ Small on purpose: it tells the model the view exists, what it broadly
30
+ answers, any authored instructions, and example questions — then points at
31
+ the describe tool for the details it needs to actually build a query.
32
+ """
33
+ s = context.summary()
34
+ lines: list[str] = []
35
+ lines.append(f"# Semantic view: {s.name}")
36
+ if s.description:
37
+ lines.append("")
38
+ lines.append(s.description.strip())
39
+
40
+ if s.custom_instructions:
41
+ lines.append("")
42
+ lines.append("## Instructions")
43
+ lines.append(s.custom_instructions.strip())
44
+
45
+ if s.verified_queries:
46
+ lines.append("")
47
+ lines.append("## Example questions this view can answer")
48
+ for vq in s.verified_queries:
49
+ lines.append(f"- {vq.question}")
50
+
51
+ lines.append("")
52
+ lines.append("## How to use this view")
53
+ lines.append(
54
+ f"You do not yet have the full list of tables, dimensions, metrics, or "
55
+ f"filterable fields for `{s.name}`. Before building a query, call "
56
+ f"`{DESCRIBE_TOOL_NAME}` with this view's name to load its full context. "
57
+ f"Then answer data questions by calling `{QUERY_TOOL_NAME}` with a "
58
+ f"semantic query that references only the names from that context — never "
59
+ f"write SQL yourself."
60
+ )
61
+ return "\n".join(lines)
62
+
63
+
64
+ def render_describe(context: SemanticContext) -> str:
65
+ """The full, on-demand context returned by the describe tool.
66
+
67
+ Covers everything the model needs to compose a valid semantic query:
68
+ every queryable dimension / fact / metric (with descriptions, synonyms and
69
+ hints), view-level metrics, and the relationships that let a query span
70
+ tables. Physical exprs and private items are already stripped upstream.
71
+ """
72
+ lines: list[str] = []
73
+ lines.append(f"# Semantic view: {context.name}")
74
+ if context.description:
75
+ lines.append("")
76
+ lines.append(context.description.strip())
77
+
78
+ if context.custom_instructions:
79
+ lines.append("")
80
+ lines.append("## Instructions")
81
+ lines.append(context.custom_instructions.strip())
82
+
83
+ for table in context.tables:
84
+ lines.append("")
85
+ lines.append(f"## Table: {table.name}")
86
+ if table.description:
87
+ lines.append(table.description.strip())
88
+
89
+ if table.dimensions:
90
+ lines.append("")
91
+ lines.append("### Dimensions (group by / filter)")
92
+ lines.extend(_item_line(i, table.name) for i in table.dimensions)
93
+
94
+ if table.facts:
95
+ lines.append("")
96
+ lines.append("### Facts (row-level values)")
97
+ lines.extend(_item_line(i, table.name) for i in table.facts)
98
+
99
+ if table.metrics:
100
+ lines.append("")
101
+ lines.append("### Metrics (aggregations)")
102
+ lines.extend(_item_line(i, table.name) for i in table.metrics)
103
+
104
+ if context.metrics:
105
+ lines.append("")
106
+ lines.append("## View-level metrics (span multiple tables)")
107
+ lines.extend(_item_line(i, None) for i in context.metrics)
108
+
109
+ if context.relationships:
110
+ lines.append("")
111
+ lines.append("## Relationships (queries may select across these)")
112
+ for r in context.relationships:
113
+ lines.append(f"- `{r.left_table}` ↔ `{r.right_table}` ({r.name})")
114
+
115
+ lines.append("")
116
+ lines.append(
117
+ f"Reference items as `table.item` (e.g. `{_example_ref(context)}`). Put "
118
+ f"row-level predicates in `filters` and metric thresholds in `having`. "
119
+ f"Build the query by calling `{QUERY_TOOL_NAME}`."
120
+ )
121
+ return "\n".join(lines)
122
+
123
+
124
+ def _item_line(item: ContextItem, table: str | None) -> str:
125
+ """One bullet per item: qualified name, type, description, synonyms, hints."""
126
+ qualified = f"{table}.{item.name}" if table else item.name
127
+ parts = [f"- `{qualified}`"]
128
+ if item.data_type:
129
+ parts.append(f"({item.data_type})")
130
+ if item.description:
131
+ parts.append(f"— {item.description.strip()}")
132
+
133
+ tags: list[str] = []
134
+ if item.synonyms:
135
+ tags.append("synonyms: " + ", ".join(item.synonyms))
136
+ if item.is_enum:
137
+ tags.append("enumerable")
138
+ if item.is_filter_hint:
139
+ tags.append("good filter")
140
+ if tags:
141
+ parts.append(f"[{'; '.join(tags)}]")
142
+ return " ".join(parts)
143
+
144
+
145
+ def _example_ref(context: SemanticContext) -> str:
146
+ """Pick a real dotted reference from the context for the closing hint."""
147
+ for table in context.tables:
148
+ for group in (table.dimensions, table.metrics, table.facts):
149
+ if group:
150
+ return f"{table.name}.{group[0].name}"
151
+ if context.metrics:
152
+ return context.metrics[0].name
153
+ return "table.item"
@@ -0,0 +1,131 @@
1
+ """Semantic Query types (SLQP Part I).
2
+
3
+ This is the contract the LLM emits and the engine compiles. The models are
4
+ deliberately shaped to be used directly as a **function-call / tool input
5
+ schema**: every field carries a description, operators are a closed enum, and
6
+ the filter tree is expressed as a discriminated union so the generated JSON
7
+ schema guides the model toward valid output.
8
+
9
+ These types capture the structure of a query. The compiler and backend validate
10
+ the semantic rules they need before execution.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Annotated, Literal
16
+
17
+ from pydantic import BaseModel, Field
18
+
19
+ # Comparison / membership / null operators, per protocol section 4.3.
20
+ Operator = Literal[
21
+ "eq",
22
+ "ne",
23
+ "gt",
24
+ "gte",
25
+ "lt",
26
+ "lte",
27
+ "in",
28
+ "not_in",
29
+ "between",
30
+ "like",
31
+ "not_like",
32
+ "is_null",
33
+ "is_not_null",
34
+ ]
35
+
36
+ Direction = Literal["asc", "desc"]
37
+
38
+ # A literal usable as a filter value: scalar, or an array for in/not_in/between.
39
+ ScalarValue = str | int | float | bool
40
+ FilterValue = ScalarValue | list[ScalarValue]
41
+
42
+
43
+ class SelectionItem(BaseModel):
44
+ """A metric / dimension / fact to select.
45
+
46
+ ``name`` must be a logical name declared in the model, qualified as
47
+ ``table.item`` or unqualified when globally unique. ``alias`` optionally
48
+ names the output column and can be referenced from ``order_by``.
49
+ """
50
+
51
+ name: str = Field(
52
+ description="Logical item name, e.g. 'customer.customer_tier' or 'total_forecast_qty'."
53
+ )
54
+ alias: str | None = Field(
55
+ default=None, description="Optional output column name; usable in order_by."
56
+ )
57
+
58
+
59
+ class FilterCondition(BaseModel):
60
+ """A leaf predicate: ``field <operator> value``.
61
+
62
+ ``value`` is a scalar for comparison ops, an array for ``in`` / ``not_in`` /
63
+ ``between`` (``[low, high]``), and omitted for ``is_null`` / ``is_not_null``.
64
+ """
65
+
66
+ field: str = Field(description="Logical item name the predicate applies to.")
67
+ operator: Operator
68
+ value: FilterValue | None = Field(
69
+ default=None,
70
+ description="Scalar for comparisons; array for in/not_in/between; omit for null tests.",
71
+ )
72
+
73
+
74
+ class FilterGroup(BaseModel):
75
+ """A boolean group combining nested conditions/groups with and/or."""
76
+
77
+ op: Literal["and", "or"]
78
+ conditions: list[FilterNode] = Field(min_length=1)
79
+
80
+
81
+ # A filter is either a group or a leaf condition. FilterGroup is tried first so
82
+ # that objects carrying an ``op`` key parse as groups.
83
+ FilterNode = Annotated[
84
+ FilterGroup | FilterCondition,
85
+ Field(union_mode="left_to_right"),
86
+ ]
87
+
88
+
89
+ class OrderBy(BaseModel):
90
+ field: str = Field(
91
+ description="A selected item name or a declared alias to sort by."
92
+ )
93
+ direction: Direction = "asc"
94
+
95
+
96
+ class SemanticQuery(BaseModel):
97
+ """A request expressed only in business terms declared by the model.
98
+
99
+ A valid query selects at least one of ``metrics`` / ``dimensions`` /
100
+ ``facts``. Selecting one or more metrics puts the query in *aggregated* mode
101
+ (grouped by the selected dimensions); otherwise it is a *detail* projection.
102
+ """
103
+
104
+ model: str = Field(description="Which semantic model to query.")
105
+ metrics: list[SelectionItem] = Field(
106
+ default_factory=list, description="Metrics to compute (aggregated mode)."
107
+ )
108
+ dimensions: list[SelectionItem] = Field(
109
+ default_factory=list, description="Attributes to group by / return."
110
+ )
111
+ facts: list[SelectionItem] = Field(
112
+ default_factory=list,
113
+ description="Row-level values returned without grouping (detail mode).",
114
+ )
115
+ filters: FilterNode | None = Field(
116
+ default=None, description="Row-level predicate (WHERE), before aggregation."
117
+ )
118
+ having: FilterNode | None = Field(
119
+ default=None, description="Predicate on metrics (HAVING), after aggregation."
120
+ )
121
+ order_by: list[OrderBy] = Field(default_factory=list)
122
+ limit: int | None = Field(default=None, ge=0)
123
+ offset: int | None = Field(default=None, ge=0)
124
+
125
+ def is_aggregated(self) -> bool:
126
+ """Aggregated mode iff at least one metric is selected."""
127
+ return len(self.metrics) > 0
128
+
129
+
130
+ # Resolve the forward reference used inside FilterGroup.conditions.
131
+ FilterGroup.model_rebuild()
@@ -0,0 +1 @@
1
+ """Framework-specific integrations."""
@@ -0,0 +1,85 @@
1
+ """LangChain agent middleware for semantic view discovery and querying."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Sequence
6
+
7
+ from langchain.agents.middleware import AgentMiddleware
8
+ from langchain.agents.middleware.types import ModelRequest, ModelResponse
9
+ from langchain_core.messages import SystemMessage
10
+
11
+ from ..core.backend import SemanticQueryBackend
12
+ from ..core.model import SemanticView
13
+ from ..core.prompt import render_summary
14
+ from .langchain_tools import build_describe_tool, build_run_query_tool
15
+
16
+ _DEFAULT_PREAMBLE = (
17
+ "Answer data questions using the semantic views below. Inspect a view with "
18
+ "`describe_semantic_view` before calling `run_semantic_query`. Do not write SQL."
19
+ )
20
+
21
+
22
+ class SemanticLayerMiddleware(AgentMiddleware):
23
+ """Provide semantic view context and query tools to a LangChain agent.
24
+
25
+ Supply a backend implementing ``execute(view, query)``.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ views: SemanticView | Sequence[SemanticView],
31
+ backend: SemanticQueryBackend,
32
+ *,
33
+ preamble: str | None = None,
34
+ max_rows_in_message: int | None = None,
35
+ ) -> None:
36
+ super().__init__()
37
+ if not callable(getattr(backend, "execute", None)):
38
+ raise TypeError("backend must implement execute(view, query)")
39
+ if max_rows_in_message is not None and max_rows_in_message < 0:
40
+ raise ValueError("max_rows_in_message must be non-negative")
41
+
42
+ view_list = [views] if isinstance(views, SemanticView) else list(views)
43
+ if not view_list:
44
+ raise ValueError("SemanticLayerMiddleware requires at least one view")
45
+ by_name: dict[str, SemanticView] = {}
46
+ for view in view_list:
47
+ if view.name in by_name:
48
+ raise ValueError(f"duplicate semantic view name: {view.name!r}")
49
+ by_name[view.name] = view
50
+ self._views_by_name = by_name
51
+ base = preamble.strip() if preamble else _DEFAULT_PREAMBLE
52
+ self._prompt_block = (
53
+ base
54
+ + "\n\n"
55
+ + "\n\n---\n\n".join(render_summary(view.context()) for view in view_list)
56
+ )
57
+ self.tools = [
58
+ build_describe_tool(by_name),
59
+ build_run_query_tool(
60
+ by_name, backend, max_rows_in_message=max_rows_in_message
61
+ ),
62
+ ]
63
+
64
+ def _augmented_system_message(self, request: ModelRequest) -> SystemMessage:
65
+ existing = request.system_prompt
66
+ content = (
67
+ f"{existing}\n\n{self._prompt_block}" if existing else self._prompt_block
68
+ )
69
+ return SystemMessage(content=content)
70
+
71
+ def wrap_model_call(
72
+ self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
73
+ ) -> ModelResponse:
74
+ return handler(
75
+ request.override(system_message=self._augmented_system_message(request))
76
+ )
77
+
78
+ async def awrap_model_call(
79
+ self,
80
+ request: ModelRequest,
81
+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
82
+ ) -> ModelResponse:
83
+ return await handler(
84
+ request.override(system_message=self._augmented_system_message(request))
85
+ )
@@ -0,0 +1,63 @@
1
+ """Agent tools for discovering and executing semantic queries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from langchain_core.tools import tool
8
+
9
+ from ..core.backend import SemanticQueryBackend
10
+ from ..core.errors import CompileError
11
+ from ..core.model import SemanticView
12
+ from ..core.prompt import render_describe
13
+ from ..core.query import SemanticQuery
14
+
15
+
16
+ def build_describe_tool(views_by_name: dict[str, SemanticView]):
17
+ known = ", ".join(views_by_name)
18
+
19
+ @tool
20
+ async def describe_semantic_view(name: str) -> str:
21
+ """Describe a semantic view's logical fields before querying it."""
22
+ view = views_by_name.get(name)
23
+ if view is None:
24
+ return f"Unknown semantic view '{name}'. Available views: {known}."
25
+ return render_describe(view.context())
26
+
27
+ return describe_semantic_view
28
+
29
+
30
+ def build_run_query_tool(
31
+ views_by_name: dict[str, SemanticView],
32
+ backend: SemanticQueryBackend,
33
+ *,
34
+ max_rows_in_message: int | None = None,
35
+ ):
36
+ @tool
37
+ async def run_semantic_query(query: SemanticQuery) -> str:
38
+ """Run a structured semantic query using names from a described view.
39
+
40
+ Put aggregations in metrics, group-by fields in dimensions, row
41
+ predicates in filters, and aggregate predicates in having. Never write SQL.
42
+ """
43
+ view = views_by_name.get(query.model)
44
+ if view is None:
45
+ return json.dumps(
46
+ {
47
+ "ok": False,
48
+ "error": f"unknown model '{query.model}'. Available views: {', '.join(views_by_name)}.",
49
+ },
50
+ ensure_ascii=False,
51
+ )
52
+ try:
53
+ rows = list(await backend.execute(view, query))
54
+ except CompileError as exc:
55
+ return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)
56
+
57
+ shown = rows if max_rows_in_message is None else rows[:max_rows_in_message]
58
+ payload = {"ok": True, "row_count": len(rows), "rows": shown}
59
+ if len(shown) != len(rows):
60
+ payload.update({"truncated": True, "shown": len(shown)})
61
+ return json.dumps(payload, ensure_ascii=False, default=str)
62
+
63
+ return run_semantic_query