skifer-databricks 4.2.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,25 @@
1
+ """
2
+ skifer.serving — Databricks Model Serving layer.
3
+
4
+ Exposes AgenticHub as an MLflow ResponsesAgent on Databricks Model Serving.
5
+
6
+ Public exports:
7
+ SkiferResponsesAgent — mlflow.pyfunc.ResponsesAgent wrapping AgenticHub (needs the serving extra)
8
+ log_agent — log the agent to MLflow with its artifacts and resources (needs the serving extra)
9
+ hub_response_to_text — convert any HubResponse to a plain text string
10
+ """
11
+
12
+ from ._response_serializer import hub_response_to_text
13
+
14
+ __all__ = ["SkiferResponsesAgent", "hub_response_to_text", "log_agent"]
15
+
16
+
17
+ def __getattr__(name: str): # noqa: N807
18
+ # Lazy: importing skifer.serving must not require MLflow.
19
+ if name == "SkiferResponsesAgent":
20
+ from .responses_agent import SkiferResponsesAgent # noqa: PLC0415
21
+ return SkiferResponsesAgent
22
+ if name == "log_agent":
23
+ from .deploy import log_agent # noqa: PLC0415
24
+ return log_agent
25
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,189 @@
1
+ """
2
+ MLflow-free core of the serving agent (Plan 41.4).
3
+
4
+ Everything the endpoint decides lives here, so it is tested without MLflow installed:
5
+ which question is asked, who declares to be asking, what text and evidence go back,
6
+ and how the hub is built at pod start. ``responses_agent.py`` only adapts these
7
+ functions to ``mlflow.pyfunc.ResponsesAgent``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from typing import Any, Mapping
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ EVIDENCE_SCHEMA_VERSION = "2"
18
+
19
+
20
+ def build_hub(
21
+ artifacts: Mapping[str, str] | None,
22
+ model_config: Mapping[str, Any] | None = None,
23
+ ) -> Any:
24
+ """Build the AgenticHub served by the endpoint; called once, at pod start.
25
+
26
+ No Spark session is passed to the engine: ``get_spark_session()`` picks
27
+ Databricks Connect serverless when ``DATABRICKS_SERVERLESS_COMPUTE_ID`` is set,
28
+ which is the only way a Model Serving container gets Spark.
29
+
30
+ ``model_config["llm_endpoint"]``, written by ``log_agent``, names the chat endpoint;
31
+ without it ``DATABRICKS_LLM_MODEL`` is required.
32
+ """
33
+ from skifer.agentic.hub import AgenticHub
34
+ from skifer.core.core import SkiferEngine
35
+ from skifer.observability.certification_store import default_certification_store
36
+ from skifer.semantic.llm_provider import get_llm_provider
37
+ from skifer.semantic.semantic import SemanticEngine
38
+
39
+ artifacts = artifacts or {}
40
+ config_path = artifacts.get("config", "config.yaml")
41
+ models_dir = artifacts.get("models_dir", "semantic")
42
+
43
+ engine = SkiferEngine(config_path=config_path)
44
+ semantic = SemanticEngine(
45
+ engine,
46
+ models_dir=models_dir,
47
+ certification_store=default_certification_store(engine),
48
+ )
49
+ llm_endpoint = (model_config or {}).get("llm_endpoint")
50
+ llm = get_llm_provider("databricks", **({"model": llm_endpoint} if llm_endpoint else {}))
51
+ candidate_agent = _build_candidate_agent(engine, semantic, llm)
52
+ if candidate_agent is None:
53
+ hub = AgenticHub(semantic_engine=semantic, llm_provider=llm)
54
+ else:
55
+ hub = AgenticHub(
56
+ semantic_engine=semantic, llm_provider=llm, candidate_agent=candidate_agent
57
+ )
58
+ logger.info("Skifer serving agent: AgenticHub initialised.")
59
+ return hub
60
+
61
+
62
+ def _build_candidate_agent(engine: Any, semantic: Any, llm: Any) -> Any:
63
+ """The Plan 44 fallback agent, or None — nothing is opened when ``candidate_fallback`` is off."""
64
+ from skifer.core.config import candidate_fallback_mode
65
+
66
+ reader = getattr(semantic, "_env_config", None)
67
+ env_config = reader() if callable(reader) else None
68
+ if candidate_fallback_mode(env_config if isinstance(env_config, dict) else None) == "off":
69
+ return None
70
+ from skifer.agentic.candidate_agent import MetricCandidateAgent
71
+ from skifer.candidates import default_candidate_store
72
+ from skifer.knowledge import KnowledgeIndex, default_knowledge_store
73
+
74
+ return MetricCandidateAgent(
75
+ semantic,
76
+ llm,
77
+ KnowledgeIndex.from_config(default_knowledge_store(engine),
78
+ env_config if isinstance(env_config, dict) else None),
79
+ default_candidate_store(engine),
80
+ policy=getattr(semantic.tracer, "attribute_policy", None),
81
+ )
82
+
83
+
84
+ def _as_dict(item: Any) -> dict:
85
+ if isinstance(item, Mapping):
86
+ return dict(item)
87
+ if hasattr(item, "model_dump"):
88
+ return item.model_dump()
89
+ return {}
90
+
91
+
92
+ def _content_text(content: Any) -> str:
93
+ if isinstance(content, str):
94
+ return content
95
+ if isinstance(content, list):
96
+ parts = [_as_dict(part).get("text") for part in content]
97
+ return "\n".join(part for part in parts if isinstance(part, str))
98
+ return ""
99
+
100
+
101
+ def extract_question(input_items: list[Any]) -> str:
102
+ """Return the text of the last ``user`` item of a Responses ``input`` list.
103
+
104
+ Items may be MLflow pydantic models or plain dicts, and a content may be a string
105
+ or a list of text parts.
106
+ """
107
+ for item in reversed(input_items or []):
108
+ data = _as_dict(item)
109
+ if data.get("role") == "user":
110
+ return _content_text(data.get("content"))
111
+ raise ValueError("Skifer serving agent: no input item with role='user' in the request.")
112
+
113
+
114
+ def consumer_context_from_request(context: Any, custom_inputs: Mapping[str, Any] | None):
115
+ """Build the ConsumerContext from client-declared request metadata, or None.
116
+
117
+ ``consumer_id``, ``user_id`` and ``trace_id`` are declared by the client, not an
118
+ authenticated Model Serving identity: they may feed consumer_class, logs and traces,
119
+ never an authorization. ``scopes`` is therefore never populated here, whatever the
120
+ request carries, so a caller cannot self-assign ``certification_override``.
121
+ """
122
+ from skifer.semantic.access_policy import ConsumerContext
123
+
124
+ custom_inputs = custom_inputs or {}
125
+ user_id = custom_inputs.get("user_id") or getattr(context, "user_id", None)
126
+ consumer_id = custom_inputs.get("consumer_id") or user_id
127
+ if not consumer_id:
128
+ return None
129
+ return ConsumerContext(
130
+ consumer_id=consumer_id,
131
+ consumer_class="agent_read",
132
+ user_id=user_id,
133
+ trace_id=custom_inputs.get("trace_id"),
134
+ )
135
+
136
+
137
+ def answer(hub: Any, question: str, consumer_context: Any) -> tuple[str, dict | None]:
138
+ """Ask the hub; return the answer text and the ``custom_outputs`` to send back.
139
+
140
+ The evidence goes into ``custom_outputs["skifer"]``, the field Responses agents
141
+ provide for it, versioned so a client can tell an evolution from a regression.
142
+ """
143
+ from skifer.observability.tracing import NoOpTracer, configured_span_scope
144
+ from skifer.serving._markdown_renderer import hub_response_to_markdown
145
+ from skifer.serving._response_serializer import semantic_evidence_to_dict
146
+
147
+ response = hub.ask(question, consumer_context=consumer_context)
148
+ tracer = getattr(hub, "tracer", None) or NoOpTracer()
149
+ required = bool(getattr(hub, "_tracing_required", False))
150
+ with configured_span_scope(tracer, "skifer.response.serialize", required=required):
151
+ evidence = semantic_evidence_to_dict(getattr(response, "evidence", None))
152
+ # Chat surfaces (Playground, supervisor) render the text as Markdown.
153
+ text = hub_response_to_markdown(response, business_labels(hub, evidence))
154
+ if evidence is None:
155
+ return text, None
156
+ return text, {"skifer": {"schema_version": EVIDENCE_SCHEMA_VERSION, "evidence": evidence}}
157
+
158
+
159
+ def business_labels(hub: Any, evidence: Mapping[str, Any] | None) -> dict[str, str]:
160
+ """Map the metric and dimension names of the answered models to their labels.
161
+
162
+ A metric's ``label``, else its ``description``, read from the semantic models the
163
+ evidence names. Presentation only, hence best-effort: a model that cannot be read
164
+ leaves the technical names in place and never fails the answer.
165
+ """
166
+ semantic = getattr(hub, "_semantic_engine", None)
167
+ if not evidence or semantic is None:
168
+ return {}
169
+ labels: dict[str, str] = {}
170
+ for model_key in evidence.get("model_keys") or ():
171
+ try:
172
+ # Already loaded and cached by the query that produced the evidence.
173
+ model = semantic._get_model(model_key)
174
+ except Exception:
175
+ logger.debug("Skifer serving agent: no labels for model %r.", model_key)
176
+ continue
177
+ if not isinstance(model, Mapping):
178
+ continue
179
+ for section in ("metrics", "dimensions"):
180
+ items = model.get(section)
181
+ if not isinstance(items, list):
182
+ continue
183
+ for item in items:
184
+ if not isinstance(item, Mapping) or not isinstance(item.get("name"), str):
185
+ continue
186
+ label = item.get("label") or item.get("description")
187
+ if isinstance(label, str) and label.strip():
188
+ labels.setdefault(item["name"], label.strip())
189
+ return labels
@@ -0,0 +1,286 @@
1
+ """
2
+ hub_response_to_markdown — renders a HubResponse as Markdown for chat surfaces.
3
+
4
+ The Databricks Playground and the Agent Bricks supervisor render the Responses
5
+ ``output`` text as Markdown: the plain-text form of ``hub_response_to_text``
6
+ loses its line breaks there and shows raw floats (``16200985.329999981``).
7
+ This renderer is used by the serving layer only; the CLI and the local API keep
8
+ the plain-text form.
9
+
10
+ The disclosure rules are those of the plain-text form: only allowlisted
11
+ evidence fields, never a filter value, and the weakest source wins on every
12
+ axis of the provenance block.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime as _dt
18
+ import math
19
+ from decimal import Decimal
20
+ from typing import Any, Mapping
21
+
22
+ from skifer.serving._response_serializer import (
23
+ CANDIDATE_WARNING_LINE,
24
+ _candidate_metric_text,
25
+ _oldest_age,
26
+ hub_response_to_text,
27
+ semantic_evidence_to_dict,
28
+ )
29
+
30
+ MAX_TABLE_ROWS = 30
31
+ # A business label longer than this is a sentence, not a column header.
32
+ MAX_LABEL_LENGTH = 48
33
+
34
+ _NUMERIC_TYPES = frozenset(
35
+ {"tinyint", "smallint", "int", "bigint", "float", "double", "decimal", "long", "short"}
36
+ )
37
+ _TEMPORAL_TYPES = frozenset({"date", "timestamp", "timestamp_ntz"})
38
+ _TEMPORAL_HINTS = (
39
+ "date", "day", "jour", "week", "semaine", "month", "mois",
40
+ "quarter", "trimestre", "year", "annee", "année", "period",
41
+ )
42
+
43
+ _NBSP = "\u00a0"
44
+
45
+ _STATUS_LABELS = {
46
+ "CERTIFIED": "✅ certifiée",
47
+ "UNCERTIFIED": "❌ non certifiée",
48
+ "MISSING": "❌ absente",
49
+ "EXPIRED": "⏰ expirée",
50
+ "NOT_EVALUATED": "⚠️ non évaluée (gate de certification désactivé)",
51
+ "OVERRIDDEN": "⚠️ contournée (override)",
52
+ }
53
+
54
+
55
+ def hub_response_to_markdown(response: Any, labels: Mapping[str, str] | None = None) -> str:
56
+ """Render a HubResponse as Markdown; ``labels`` maps technical names to business labels.
57
+
58
+ Only semantic answers (``AgentResponse``) get a dedicated rendering; the other
59
+ responses keep their plain-text form, which is already readable as Markdown.
60
+ """
61
+ from skifer.agentic.models import AgentResponse
62
+
63
+ if not isinstance(response, AgentResponse):
64
+ return hub_response_to_text(response)
65
+ body = _agent_body(response, dict(labels or {}))
66
+ if response.mode == "candidate":
67
+ body = f"{CANDIDATE_WARNING_LINE}\n\n{body}"
68
+ evidence = getattr(response, "evidence", None)
69
+ if evidence is None:
70
+ evidence = getattr(getattr(response, "result", None), "evidence", None)
71
+ payload = semantic_evidence_to_dict(evidence)
72
+ if payload is None:
73
+ return body
74
+ # The blank line matters: "---" right under a paragraph is a setext heading.
75
+ return f"{body}\n\n---\n{_provenance_block(payload)}"
76
+
77
+
78
+ def _agent_body(response: Any, labels: dict[str, str]) -> str:
79
+ from skifer.agentic.models import ResponseFormat
80
+
81
+ if response.mode == "error":
82
+ if getattr(response, "access_denied", False):
83
+ decision = response.policy_decision or "DENY"
84
+ reasons = ", ".join(response.policy_reasons or ()) or "non précisée"
85
+ action = response.recommended_action or "Contacter le propriétaire de la donnée."
86
+ return f"⛔ **Accès refusé** ({decision}) — raison : {reasons}.\n\n{action}"
87
+ return f"⚠️ **Impossible de répondre** : {response.error}"
88
+
89
+ if response.mode in ("ambiguous", "needs_clarification"):
90
+ question = response.clarification_question or response.explanation
91
+ return f"🤔 {question or 'Pouvez-vous préciser la question ?'}"
92
+
93
+ result = getattr(response, "result", None)
94
+ if result is None:
95
+ return response.explanation or "Réponse reçue."
96
+
97
+ fmt = getattr(result, "format", None)
98
+ title = getattr(result, "title", "") or ""
99
+
100
+ if fmt == ResponseFormat.KPI:
101
+ name = result.kpi_label or ""
102
+ lines = [f"**{_escape(_label(name, labels) or title or 'Valeur')}**"]
103
+ if title and title != name:
104
+ lines.append(f"_{_escape(title)}_")
105
+ lines += ["", f"### {_format_value(result.kpi_value)}"]
106
+ return "\n".join(lines)
107
+
108
+ table = _markdown_table(getattr(result, "data", None), labels)
109
+ if fmt in (ResponseFormat.TABLE, ResponseFormat.CHART):
110
+ heading = f"**{_escape(title)}**" if title else ""
111
+ if table is None:
112
+ return heading or "Aucune donnée."
113
+ return f"{heading}\n\n{table}" if heading else table
114
+
115
+ summary = getattr(result, "text_summary", None) or response.explanation
116
+ parts = [summary or "Réponse reçue."]
117
+ if table is not None:
118
+ parts.append(f"**Détail**\n\n{table}")
119
+ return "\n\n".join(parts)
120
+
121
+
122
+ def _label(name: str, labels: Mapping[str, str]) -> str:
123
+ label = labels.get(name)
124
+ if label and len(label) <= MAX_LABEL_LENGTH:
125
+ return label
126
+ return name.replace("_", " ").strip().capitalize()
127
+
128
+
129
+ def _markdown_table(data: Any, labels: Mapping[str, str]) -> str | None:
130
+ if data is None:
131
+ return None
132
+ try:
133
+ # One row more than shown, only to know whether the table was cut.
134
+ rows = _display_order(data).limit(MAX_TABLE_ROWS + 1).collect()
135
+ columns = list(data.columns)
136
+ except Exception:
137
+ return None
138
+ if not rows:
139
+ return "_Aucune ligne._"
140
+
141
+ values = [list(row) for row in rows[:MAX_TABLE_ROWS]]
142
+ numeric = [
143
+ any(_is_number(row[index]) for row in values)
144
+ and all(row[index] is None or _is_number(row[index]) for row in values)
145
+ for index in range(len(columns))
146
+ ]
147
+ lines = [
148
+ "| " + " | ".join(_escape(_label(column, labels)) for column in columns) + " |",
149
+ "| " + " | ".join("---:" if flag else "---" for flag in numeric) + " |",
150
+ ]
151
+ lines += [
152
+ "| " + " | ".join(_escape(_format_value(value)) for value in row) + " |"
153
+ for row in values
154
+ ]
155
+ table = "\n".join(lines)
156
+ if len(rows) > MAX_TABLE_ROWS:
157
+ table += f"\n\n_{MAX_TABLE_ROWS} premières lignes affichées._"
158
+ return table
159
+
160
+
161
+ def _display_order(data: Any) -> Any:
162
+ """Order a breakdown for reading: a time axis ascending, else the first measure descending.
163
+
164
+ The semantic query has no ORDER BY, so rows come back in whatever order Spark
165
+ produced them — and the rows kept under the cap would be arbitrary too.
166
+ """
167
+ try:
168
+ dtypes = [(str(name), str(kind).split("(")[0].lower()) for name, kind in data.dtypes]
169
+ except Exception:
170
+ return data
171
+ numeric = [name for name, kind in dtypes if kind in _NUMERIC_TYPES]
172
+ temporal = [
173
+ name
174
+ for name, kind in dtypes
175
+ if name not in numeric
176
+ and (kind in _TEMPORAL_TYPES or any(hint in name.lower() for hint in _TEMPORAL_HINTS))
177
+ ]
178
+ if temporal:
179
+ return data.orderBy(*temporal)
180
+ if numeric and len(numeric) < len(dtypes):
181
+ return data.orderBy(numeric[0], ascending=False)
182
+ return data
183
+
184
+
185
+ def _is_number(value: Any) -> bool:
186
+ return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
187
+
188
+
189
+ def _format_value(value: Any) -> str:
190
+ """French display: narrow grouping, decimal comma, two decimals at most."""
191
+ if value is None:
192
+ return "—"
193
+ if isinstance(value, bool):
194
+ return "oui" if value else "non"
195
+ if isinstance(value, int):
196
+ return _french(f"{value:,}")
197
+ if isinstance(value, (float, Decimal)):
198
+ number = float(value)
199
+ if math.isnan(number) or math.isinf(number):
200
+ return str(value)
201
+ if number == int(number):
202
+ return _french(f"{int(number):,}")
203
+ if abs(number) >= 1:
204
+ return _french(f"{number:,.2f}")
205
+ # A ratio or a share: two decimals would round 0.004 to zero.
206
+ return _french(f"{number:.4g}")
207
+ if isinstance(value, _dt.datetime):
208
+ return value.isoformat(sep=" ", timespec="minutes")
209
+ if isinstance(value, _dt.date):
210
+ return value.isoformat()
211
+ return str(value)
212
+
213
+
214
+ def _french(text: str) -> str:
215
+ return text.replace(",", _NBSP).replace(".", ",")
216
+
217
+
218
+ def _escape(text: str) -> str:
219
+ return str(text).replace("|", "\\|").replace("\n", " ")
220
+
221
+
222
+ def _provenance_block(evidence: dict[str, Any]) -> str:
223
+ lines = ["**Provenance**"]
224
+ if evidence["execution_status"] == "failed":
225
+ lines.append("- ❌ Exécution incomplète (échec)")
226
+
227
+ sources = evidence["sources"]
228
+ if not sources:
229
+ lines += ["- Source : inconnue", "- Certification : inconnue", "- Fraîcheur : inconnue"]
230
+ return "\n".join(lines)
231
+
232
+ names = [source["dataset"] for source in sources]
233
+ shown = ", ".join(f"`{name}`" for name in names[:3])
234
+ if len(names) > 3:
235
+ shown += f" (+{len(names) - 3})"
236
+ lines.append(f"- {'Source' if len(names) == 1 else 'Sources'} : {shown}")
237
+ lines.append(
238
+ f"- Certification : {_certification(sources, evidence.get('metrics') or [])}"
239
+ )
240
+ lines.append(f"- Fraîcheur : {_freshness(_oldest_age(sources))}")
241
+
242
+ decision = evidence["policy"]["decision"]
243
+ if decision and decision != "ALLOW":
244
+ lines.append(f"- Décision du gate : {decision.lower()}")
245
+ return "\n".join(lines)
246
+
247
+
248
+ def _status_label(status: str | None) -> str:
249
+ if not status:
250
+ return "❓ inconnue"
251
+ return _STATUS_LABELS.get(status, f"❓ {status.lower()}")
252
+
253
+
254
+ def _certification(
255
+ sources: list[dict[str, Any]], metrics: list[dict[str, Any]] = ()
256
+ ) -> str:
257
+ # Plan 44, D4: an uncertified metric wins over certified sources.
258
+ candidate_text = _candidate_metric_text(list(metrics))
259
+ if candidate_text is not None:
260
+ return f"⚠️ {candidate_text}"
261
+ weak = [source for source in sources if source["certification_status"] != "CERTIFIED"]
262
+ if weak:
263
+ if len(sources) == 1:
264
+ return _status_label(weak[0]["certification_status"])
265
+ detail = ", ".join(
266
+ f"`{source['dataset']}` {_status_label(source['certification_status'])}"
267
+ for source in weak[:3]
268
+ )
269
+ return f"incomplète — {detail}"
270
+ dates = sorted(source["certified_at"] for source in sources if source["certified_at"])
271
+ if not dates:
272
+ return "✅ certifiée (date inconnue)"
273
+ # Oldest certification: the answer is only as fresh as its stalest guarantee.
274
+ return f"✅ certifiée le {dates[0][:10]}"
275
+
276
+
277
+ def _freshness(age_seconds: float | None) -> str:
278
+ if age_seconds is None:
279
+ return "non mesurée"
280
+ if age_seconds < 60:
281
+ return f"il y a {int(age_seconds)} s"
282
+ if age_seconds < 3600:
283
+ return f"il y a {int(age_seconds // 60)} min"
284
+ if age_seconds < 48 * 3600:
285
+ return f"il y a {int(age_seconds // 3600)} h"
286
+ return f"il y a {int(age_seconds // 86400)} j"