helios-semantic 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ """Helios: build semantic models of your data and query them (burndown 6.6).
2
+
3
+ from helios_semantic import Helios
4
+
5
+ helios = Helios.from_settings() # helios.toml, HELIOS_* variables, defaults
6
+ helios.models()
7
+ helios.query(["revenue"], ["shop.customers.c_region"]).records()
8
+
9
+ ``Helios`` is a facade over the libraries this package installs: helios-cortex (settings,
10
+ compiler, engines, registry, the ``helios`` command), helios-model (discovery and
11
+ publishing) and helios-serve (the tools). Extras add the rest:
12
+ ``pip install "helios-semantic[cloudera,llm]"``.
13
+ """
14
+
15
+ _EXPORTS = {name: "facade" for name in ("Helios", "HeliosError", "CompiledQuery", "QueryResult")}
16
+
17
+ __all__ = sorted(_EXPORTS)
18
+
19
+
20
+ def __getattr__(name: str):
21
+ # Exports are imported on first use, so importing helios_semantic loads nothing heavy.
22
+ if name in _EXPORTS:
23
+ from importlib import import_module
24
+
25
+ return getattr(import_module(f"helios_semantic.{_EXPORTS[name]}"), name)
26
+ if name == "__version__":
27
+ from importlib.metadata import PackageNotFoundError, version
28
+
29
+ try:
30
+ return version("helios-semantic")
31
+ except PackageNotFoundError: # running from a source path without an install
32
+ return "0.0.0+unknown"
33
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,210 @@
1
+ """The ``Helios`` facade: one object for a developer's program.
2
+
3
+ helios = Helios.from_settings()
4
+ helios.models() # the published models
5
+ helios.search("revenue by region") # what a question involves
6
+ helios.compile(["revenue"], ["shop.customers.c_region"]).sql
7
+ helios.query(["revenue"], ["shop.customers.c_region"]).records()
8
+ helios.publish("20261110T120000Z", accept_pending=True) # a discovery run's reviewed proposals
9
+
10
+ Each method calls the helios-serve tool of the same purpose (or helios-model's
11
+ ``Publisher``) and raises ``HeliosError`` where the tool returns an error.
12
+
13
+ Who runs the queries: a facade built with no caller is one user's program, running with
14
+ the configured credentials, so a connection in ``service`` identity mode runs its
15
+ queries (helios-serve's ``single_user_policy``). ``Helios.from_settings(caller=...)`` or
16
+ ``helios.as_caller(caller)`` act for that caller instead: the warehouse runs the query as
17
+ them (``impersonate`` or ``token`` mode) and a service-identity connection refuses, as in
18
+ every shared deployment. A host serving many users gives each request its own
19
+ ``as_caller``, or uses helios-serve's tools directly.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import dataclasses
24
+ import os
25
+ from collections.abc import Sequence
26
+ from dataclasses import dataclass
27
+ from typing import TYPE_CHECKING, Any
28
+
29
+ from helios_cortex.caller import Caller
30
+
31
+ if TYPE_CHECKING:
32
+ from helios_cortex.settings import Settings
33
+ from helios_model import Proposals, Publication
34
+ from helios_serve import Registry, Stores
35
+
36
+
37
+ class HeliosError(Exception):
38
+ """What a tool refused or could not do: ``code`` (helios-serve's error codes, such as
39
+ ``invalid_semantic_query`` or ``model_not_found``), ``message`` and ``retryable``."""
40
+
41
+ def __init__(self, code: str, message: str, *, retryable: bool = False):
42
+ super().__init__(f"{code}: {message}")
43
+ self.code = code
44
+ self.message = message
45
+ self.retryable = retryable
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class CompiledQuery:
50
+ sql: str
51
+ dialect: str
52
+ dataset: str # the fact table
53
+ joins: tuple[str, ...] # the other tables it joins
54
+ columns: tuple[str, ...]
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class QueryResult:
59
+ sql: str
60
+ columns: tuple[str, ...]
61
+ rows: tuple[tuple[Any, ...], ...]
62
+ dataset: str
63
+ joins: tuple[str, ...]
64
+
65
+ def records(self) -> list[dict[str, Any]]:
66
+ """The rows as dicts by column name."""
67
+ return [dict(zip(self.columns, row)) for row in self.rows]
68
+
69
+
70
+ def _list(value: str | Sequence[str] | None) -> list[str] | None:
71
+ if value is None:
72
+ return None
73
+ return [value] if isinstance(value, str) else list(value)
74
+
75
+
76
+ class Helios:
77
+ """Published semantic models, for one caller (None: this program's own user)."""
78
+
79
+ def __init__(self, stores: Stores, *, caller: Caller | None = None, registry: Registry | None = None):
80
+ self.stores = stores
81
+ self.caller = caller
82
+ self._registry = registry
83
+
84
+ @classmethod
85
+ def from_settings(cls, settings: Settings | None = None, *, profile: str | None = None,
86
+ config: str | os.PathLike[str] | None = None, caller: Caller | None = None,
87
+ **overrides: Any) -> Helios:
88
+ """The registry and published models ``settings`` name (default: ``load_settings``
89
+ with ``profile`` and ``config``, as the ``helios`` command reads them).
90
+ ``overrides`` replace parts of helios-serve's ``Stores`` (``visibility``,
91
+ ``data_policy``, ``audit``, ``engines``, ``catalogs``, ``registry``, ``models``)."""
92
+ from helios_serve import Stores, single_user_policy
93
+
94
+ if settings is None:
95
+ from helios_cortex.settings import load_settings
96
+
97
+ settings = load_settings(profile, config)
98
+ elif profile is not None or config is not None:
99
+ raise TypeError("pass settings, or profile/config to load them, not both")
100
+ if caller is None and "data_policy" not in overrides:
101
+ overrides["data_policy"] = single_user_policy()
102
+ return cls(Stores.from_settings(settings, **overrides), caller=caller)
103
+
104
+ def as_caller(self, caller: Caller | None) -> Helios:
105
+ """The same models, acting for ``caller``: queries run as them, under the default
106
+ data policy (the warehouse enforces their access) unless the host set its own."""
107
+ from helios_cortex.data_authorization import DataPolicy
108
+ from helios_serve.stores import SingleUserAuthorizer
109
+
110
+ stores = self.stores
111
+ if caller is not None and isinstance(stores.data_policy.platform, SingleUserAuthorizer):
112
+ stores = dataclasses.replace(stores, data_policy=DataPolicy(restrictions=stores.data_policy.restrictions))
113
+ return Helios(stores, caller=caller, registry=self._registry)
114
+
115
+ @property
116
+ def settings(self) -> Settings:
117
+ return self.stores.settings
118
+
119
+ @property
120
+ def tools(self) -> Registry:
121
+ """helios-serve's tool registry, for a program that offers the tools to an agent."""
122
+ if self._registry is None:
123
+ from helios_serve import load_registry
124
+
125
+ self._registry = load_registry()
126
+ return self._registry
127
+
128
+ def _call(self, name: str, **arguments: Any) -> dict[str, Any]:
129
+ from helios_serve import tools
130
+
131
+ result = getattr(tools, name)(self.caller, self.stores, **arguments)
132
+ if isinstance(result, dict) and result.get("error"):
133
+ raise HeliosError(str(result["error"]), str(result.get("message") or result["error"]),
134
+ retryable=result.get("retryable") is True)
135
+ return result
136
+
137
+ # ------------------------------------------------------------------ reading
138
+ def models(self) -> list[dict[str, Any]]:
139
+ """The published models this caller may see: ``[{"name", "status"}]``."""
140
+ return self._call("list_models")["models"]
141
+
142
+ def describe(self, model: str | None = None) -> dict[str, Any]:
143
+ """A model's datasets, fields, metrics and relationships (the first model by default)."""
144
+ return self._call("describe_model", model=model)
145
+
146
+ def search(self, question: str, *, limit: int = 10, model: str | None = None) -> list[dict[str, Any]]:
147
+ """The datasets, fields and metrics ``question`` involves, best first."""
148
+ return self._call("search_semantics", question=question, limit=limit, model=model)["matches"]
149
+
150
+ def compile(self, metrics: str | Sequence[str], dimensions: str | Sequence[str] | None = None,
151
+ filters: Sequence[dict[str, Any]] | None = None, *, limit: int = 100, dialect: str | None = None,
152
+ model: str | None = None) -> CompiledQuery:
153
+ """The SQL for ``metrics`` by ``dimensions`` (database.table.column), filtered by
154
+ ``filters`` (``{"column", "op", "value"}``), in ``dialect`` (default: the model's
155
+ own warehouse's)."""
156
+ compiled = self._call("compile_query", metrics=_list(metrics), dimensions=_list(dimensions),
157
+ filters=list(filters) if filters is not None else None, limit=limit,
158
+ dialect=dialect, model=model)
159
+ return CompiledQuery(compiled["sql"], compiled["dialect"], compiled["dataset"], tuple(compiled["joins"]),
160
+ tuple(compiled["columns"]))
161
+
162
+ def query(self, metrics: str | Sequence[str], dimensions: str | Sequence[str] | None = None,
163
+ filters: Sequence[dict[str, Any]] | None = None, *, limit: int = 100,
164
+ model: str | None = None) -> QueryResult:
165
+ """Compile and run on the model's warehouse, as this facade's caller. Values are
166
+ as the engine returns them (``Decimal``, ``date``, ...)."""
167
+ result = self._call("query_values", metrics=_list(metrics), dimensions=_list(dimensions),
168
+ filters=list(filters) if filters is not None else None, limit=limit, model=model)
169
+ return QueryResult(result["sql"], tuple(result["columns"]), tuple(tuple(r) for r in result["rows"]),
170
+ result["dataset"], tuple(result["joins"]))
171
+
172
+ def health(self, *, deep: bool = False) -> dict[str, Any]:
173
+ """helios-serve's ``health``: the registry and the models, and with ``deep`` the
174
+ warehouse connections and the catalog."""
175
+ from helios_serve import health
176
+
177
+ return health(self.stores, deep=deep)
178
+
179
+ # ------------------------------------------------------------------ publishing
180
+ def publish(self, proposals: Proposals | str, *, accept_pending: bool = False,
181
+ min_confidence: float | None = None) -> Publication:
182
+ """Publish a discovery run's reviewed proposals (``Proposals``, or the run id) as
183
+ the model's new active revision, recorded as published by this facade's caller.
184
+ ``accept_pending`` (or ``min_confidence``) first accepts the elements nobody has
185
+ decided on, as ``helios publish --accept-pending`` does. The model must be in the
186
+ registry. Raises HeliosError (``model_not_registered``, ``publication_invalid`` or
187
+ ``discovery_failed``) before writing anything."""
188
+ from helios_model import DiscoveryError, ModelNotRegistered, Proposer, Publisher
189
+ from helios_model.publication import PublicationValidationError
190
+
191
+ artifacts = getattr(self.stores.models, "artifacts", None)
192
+ try:
193
+ proposer = Proposer(self.settings, artifacts=artifacts)
194
+ if isinstance(proposals, str):
195
+ proposals = proposer.load(proposals)
196
+ if accept_pending or min_confidence is not None:
197
+ proposals.accept_all(min_confidence or 0.0)
198
+ proposer.save_review(proposals, self.caller)
199
+ publisher = Publisher(self.settings, registry=self.stores.registry, artifacts=artifacts)
200
+ return publisher.publish(proposals, self.caller)
201
+ except ModelNotRegistered as exc:
202
+ raise HeliosError("model_not_registered", str(exc)) from exc
203
+ except PublicationValidationError as exc:
204
+ raise HeliosError("publication_invalid", str(exc)) from exc
205
+ except DiscoveryError as exc:
206
+ raise HeliosError("discovery_failed", str(exc)) from exc
207
+
208
+ def __repr__(self) -> str:
209
+ who = self.caller.username if self.caller is not None and self.caller.username else "this program's user"
210
+ return f"Helios(caller={who!r})"
File without changes
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: helios-semantic
3
+ Version: 0.3.0
4
+ Summary: Helios: build semantic models of your data and query them; the package a developer installs
5
+ Project-URL: Homepage, https://github.com/christopheraburns/helios
6
+ Project-URL: Documentation, https://github.com/christopheraburns/helios/tree/main/packages/helios-semantic#readme
7
+ Project-URL: Repository, https://github.com/christopheraburns/helios
8
+ Project-URL: Issues, https://github.com/christopheraburns/helios/issues
9
+ Author: Helios Team
10
+ License-Expression: Apache-2.0
11
+ Keywords: duckdb,llm,ossie,semantic layer,semantic model,text-to-sql
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: helios-cortex>=0.3.0
24
+ Requires-Dist: helios-model>=0.3.0
25
+ Requires-Dist: helios-serve>=0.3.0
26
+ Provides-Extra: all
27
+ Requires-Dist: helios-cloudera>=0.3.0; extra == 'all'
28
+ Requires-Dist: helios-cortex[azure]>=0.3.0; extra == 'all'
29
+ Requires-Dist: helios-cortex[gcs]>=0.3.0; extra == 'all'
30
+ Requires-Dist: helios-cortex[llm]>=0.3.0; extra == 'all'
31
+ Requires-Dist: helios-cortex[ontology]>=0.3.0; extra == 'all'
32
+ Requires-Dist: helios-cortex[ozone]>=0.3.0; extra == 'all'
33
+ Requires-Dist: helios-cortex[postgres]>=0.3.0; extra == 'all'
34
+ Requires-Dist: helios-cortex[s3]>=0.3.0; extra == 'all'
35
+ Requires-Dist: helios-cortex[trino]>=0.3.0; extra == 'all'
36
+ Requires-Dist: helios-mcp>=0.3.0; extra == 'all'
37
+ Requires-Dist: helios-serve[eval]>=0.3.0; extra == 'all'
38
+ Provides-Extra: azure
39
+ Requires-Dist: helios-cortex[azure]>=0.3.0; extra == 'azure'
40
+ Provides-Extra: cloudera
41
+ Requires-Dist: helios-cloudera>=0.3.0; extra == 'cloudera'
42
+ Provides-Extra: gcs
43
+ Requires-Dist: helios-cortex[gcs]>=0.3.0; extra == 'gcs'
44
+ Provides-Extra: llm
45
+ Requires-Dist: helios-cortex[llm]>=0.3.0; extra == 'llm'
46
+ Requires-Dist: helios-serve[eval]>=0.3.0; extra == 'llm'
47
+ Provides-Extra: mcp
48
+ Requires-Dist: helios-mcp>=0.3.0; extra == 'mcp'
49
+ Provides-Extra: ontology
50
+ Requires-Dist: helios-cortex[ontology]>=0.3.0; extra == 'ontology'
51
+ Provides-Extra: ozone
52
+ Requires-Dist: helios-cortex[ozone]>=0.3.0; extra == 'ozone'
53
+ Provides-Extra: postgres
54
+ Requires-Dist: helios-cortex[postgres]>=0.3.0; extra == 'postgres'
55
+ Provides-Extra: s3
56
+ Requires-Dist: helios-cortex[s3]>=0.3.0; extra == 's3'
57
+ Provides-Extra: trino
58
+ Requires-Dist: helios-cortex[trino]>=0.3.0; extra == 'trino'
59
+ Description-Content-Type: text/markdown
60
+
61
+ # helios-semantic
62
+
63
+ Helios builds semantic models of your data (datasets, fields, metrics, relationships)
64
+ and answers questions with them: it compiles metrics and dimensions to SQL and runs it on
65
+ your warehouse as the person asking. This is the package to install.
66
+
67
+ ```sh
68
+ pip install helios-semantic # DuckDB and SQLite, on a laptop
69
+ pip install "helios-semantic[cloudera,llm]" # Impala and Atlas; an LLM to propose models
70
+ ```
71
+
72
+ ## The `Helios` facade
73
+
74
+ ```python
75
+ from helios_semantic import Helios
76
+
77
+ helios = Helios.from_settings() # helios.toml, HELIOS_* variables, then defaults
78
+
79
+ helios.models() # [{"name": "shop", "status": "published"}]
80
+ helios.search("revenue by region") # the datasets, fields and metrics involved
81
+ helios.compile(["revenue"], ["shop.customers.c_region"]).sql
82
+ result = helios.query(["revenue"], ["shop.customers.c_region"],
83
+ filters=[{"column": "shop.customers.c_region", "op": "=", "value": "east"}])
84
+ result.records() # [{"c_region": "east", "revenue": 3750.0}]
85
+
86
+ helios.publish("20261110T120000Z", accept_pending=True) # a discovery run's proposals
87
+ helios.health()
88
+ ```
89
+
90
+ A method raises `HeliosError` (with `code`, `message` and `retryable`) where a tool
91
+ refuses: an unknown metric is `invalid_semantic_query`, a model nobody published
92
+ `model_not_found`.
93
+
94
+ **Who runs the queries.** `Helios.from_settings()` with no caller is your own program,
95
+ running with the credentials you configured, so a connection in `service` identity mode
96
+ runs its queries. `Helios.from_settings(caller=Caller("alice"))`, or
97
+ `helios.as_caller(Caller("alice"))`, acts for alice: the warehouse runs the query as her
98
+ (`impersonate` or `token` mode) and enforces her permissions, and a service-identity
99
+ connection refuses. A server for many users gives each request its own `as_caller`, or
100
+ uses helios-serve's tools directly.
101
+
102
+ ## The `helios` command
103
+
104
+ ```sh
105
+ helios init # a starter helios.toml
106
+ helios init --sample # or a sample project: a TPC-DS star in DuckDB, its model published
107
+ helios harvest --source warehouse --database shop --model shop
108
+ helios profile && helios propose && helios publish --accept-pending
109
+ helios eval sample-suite.json # with [llm]: score an LLM on the sample's questions
110
+ ```
111
+
112
+ ## Extras
113
+
114
+ | Extra | Adds |
115
+ |---|---|
116
+ | `cloudera` | helios-cloudera: the Impala engine, the Atlas catalog, the Workbench settings profile |
117
+ | `llm` | an LLM client, to propose models and run `helios eval` |
118
+ | `postgres`, `trino` | a Postgres registry and engine; the Trino engine |
119
+ | `s3`, `azure`, `gcs`, `ozone` | published models on object storage |
120
+ | `ontology` | LinkML ontology parsing |
121
+ | `mcp` | helios-mcp: `helios mcp`, the tools over MCP for your coding agent |
122
+ | `all` | all of the above |
123
+
124
+ ## The libraries
125
+
126
+ helios-semantic installs helios-cortex (settings, compiler, engines, registry, the
127
+ `helios` command), helios-model (harvest, profile, propose, publish) and helios-serve
128
+ (the tools, their registry, health and evaluation). Use them directly for more control;
129
+ helios-mcp (a local MCP server for your agent) and helios-cloudera install separately.
@@ -0,0 +1,6 @@
1
+ helios_semantic/__init__.py,sha256=kEjDLVVP2UR5toY38gTHMJkQrQCv_7SaYnZUP1KF6Ck,1346
2
+ helios_semantic/facade.py,sha256=C0Jy_CraMwXh26Wl1PhXfzG81P9MgpKCZTGc_iPbY9U,10518
3
+ helios_semantic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ helios_semantic-0.3.0.dist-info/METADATA,sha256=ICZPOlW9GREeR-m5hLCkxdHTqr8Xi2mRXnj1hBXf0m0,5963
5
+ helios_semantic-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ helios_semantic-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any