Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(llms): record the per-call model in provenance entries (#2051) (#2055)
Fares Rafat0934ae80021a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9dc0d4e7..272fe29d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **LLM provenance recorded the constructor's model, so a per-call `model=` was misattributed** (fixes #2051) by @faresrafat3+ - `_track_llm_call()` resolved the model from `self.model`, the value the wrapper was constructed with, so a call that passed its own `model=` was recorded under a model the request never used. The recorded entry now names the model the call actually used: a per-call `model=` wins, and a call that passes none keeps the constructor's model+ - The rule lives in the shared recorder, so all four wrappers (`Groq`, `OpenAI`, `HuggingFace`, `LiteLLM`) inherit it on the `generate()` path and on the `generate_structured()` / `generate_typed()` paths, which reach the recorder through `_track_generation()`. The failure path that #2016 adds reaches the same recorder and inherits the rule too: the four `generate()` failure call sites forward the per-call value alongside the other options, so a failed `generate(model=...)` names the same model a successful one would+ - `HuggingFace` is the exception, and it is not a provenance rule: its provider loads the model in its constructor and reads only the generation options, so a per-call `model=` is forwarded and then ignored. Its entries keep naming the constructor model, which is the model the call actually used. `LiteLLM` currently raises on a per-call `model=` before the call reaches the provider, which is a separate defect in that provider+ - A per-call `model=` is recorded when it is a string that names a model — its `strip()` is not empty — and it is recorded as given. Every other value falls back to the constructor's model, the way a call that passes no model at all does: absent, `None`, a value that is not a string, an empty string and a whitespace-only string all name no model and are never recorded as one. A value that is not a string is dropped before it reaches the metadata, so it can no longer make the storage layer fail to serialize the entry and lose the write altogether+ - No other recorded field changes: the token counts, the cost, the latency, the activity times and the previews are what they were+ - New tests in `tests/provenance/test_llms_provenance_tracking.py` cover the override, the fallback for every value that names no model, the structured and typed paths and a direct call to the recorder, on every wrapper; one test writes through a real `ProvenanceManager` over sqlite to prove the entry is stored+- **`semantica pipeline validate` reported a partly malformed file valid, and `--json` had no structured result** (fixes #2026) by @ALDRIN121- `PipelineBuilder.build_pipeline()` keeps a step only when both `name` and `type` are truthy, so a half-written step was dropped before the validator saw it and the file was reported valid. `_load_pipeline_file()` now checks every entry while the index is still known and rejects the file, naming the offending one (`steps[1] ('broken') is missing a non-empty 'type'`). A step that is not a mapping used to reach `dict()` inside `deserialize_pipeline()` and surface as `dictionary update sequence element #0 has length 1; 2 is required`; it is now reported as `steps[0] is not a mapping (got str)`. `pipeline run` loads through the same helper, so it no longer executes a pipeline that is silently missing a step- `validate --json` now always emits `{valid, errors, warnings, pipeline}` on stdout — including when the loader or the builder inside it rejects the file, which previously fell through to the generic `{"error": ...}` envelope on stderr. When the builder raises, its `Pipeline validation failed: [...]` message is split back into one string per error instead of one reprdiff --git a/semantica/llms/llms_provenance.py b/semantica/llms/llms_provenance.pyindex 17fdd27a..21ef3997 100644--- a/semantica/llms/llms_provenance.py+++ b/semantica/llms/llms_provenance.py@@ -123,6 +123,15 @@ class LLMProvenanceMixin:"""Track LLM API call with provenance.+ The recorded model is resolved here, once, so every path that writes+ an entry inherits the same rule (#2051): a per-call ``model=`` is+ recorded when it is a string that names a model - its ``strip()`` is+ not empty - and any other value falls back to the model the wrapper+ was constructed with. That covers a value that is absent, ``None``,+ not a string, empty or whitespace-only; a value that names no model is+ never recorded as one, and a value that is not a string never costs+ the caller the entry.+Args:call_id: Unique identifier for this API callprompt: Input prompt@@ -149,6 +158,19 @@ class LLMProvenanceMixin:activity_started_at_time = metadata.pop("activity_started_at_time", None)activity_ended_at_time = metadata.pop("activity_ended_at_time", None)+ # Resolve the model once, here, so every path that writes an entry+ # inherits the same rule (#2051): a per-call ``model=`` wins when+ # it names a model, and anything else - absent, None, empty, blank+ # or not a string - falls back to the model the wrapper was+ # constructed with. The call sites only forward the raw value;+ # they never choose what gets recorded.+ per_call_model = metadata.pop("model", None)+ entry_model = (+ per_call_model+ if isinstance(per_call_model, str) and per_call_model.strip()+ else getattr(self, "model", "unknown")+ )+self._prov_manager.track_entity(entity_id=call_id,source=f"{self.__class__.__name__}_api",@@ -160,7 +182,7 @@ class LLMProvenanceMixin:activity_started_at_time=activity_started_at_time,activity_ended_at_time=activity_ended_at_time,metadata={- "model": getattr(self, 'model', 'unknown'),+ "model": entry_model,"prompt_preview": prompt[:200] if len(prompt) > 200 else prompt,"response_preview": response_preview,**metadata@@ -321,6 +343,7 @@ class GroqLLMWithProvenance(LLMProvenanceMixin):e,start_time,activity_started_at_time,+ model=kwargs.get("model"),temperature=kwargs.get("temperature"),max_tokens=kwargs.get("max_tokens"),top_p=kwargs.get("top_p"),@@ -358,6 +381,7 @@ class GroqLLMWithProvenance(LLMProvenanceMixin):latency_seconds=elapsed,activity_started_at_time=activity_started_at_time,activity_ended_at_time=activity_ended_at_time,+ model=kwargs.get("model"),temperature=kwargs.get('temperature'),max_tokens=kwargs.get('max_tokens'),top_p=kwargs.get('top_p')@@ -372,6 +396,7 @@ class GroqLLMWithProvenance(LLMProvenanceMixin):"groq_structured",prompt,lambda: self._llm.generate_structured(prompt, **kwargs),+ model=kwargs.get("model"),)def generate_typed(self, prompt: str, schema, max_retries: int = 3, **kwargs):@@ -384,6 +409,7 @@ class GroqLLMWithProvenance(LLMProvenanceMixin):prompt, schema, max_retries=max_retries, **kwargs),max_retries=max_retries,+ model=kwargs.get("model"),)def __getattr__(self, name):@@ -446,6 +472,7 @@ class OpenAILLMWithProvenance(LLMProvenanceMixin):e,start_time,activity_started_at_time,+ model=kwargs.get("model"),temperature=kwargs.get("temperature"),max_tokens=kwargs.get("max_tokens"),)@@ -482,6 +509,7 @@ class OpenAILLMWithProvenance(LLMProvenanceMixin):latency_seconds=elapsed,activity_started_at_time=activity_started_at_time,activity_ended_at_time=activity_ended_at_time,+ model=kwargs.get("model"),temperature=kwargs.get('temperature'),max_tokens=kwargs.get('max_tokens'))@@ -495,6 +523,7 @@ class OpenAILLMWithProvenance(LLMProvenanceMixin):"openai_structured",prompt,lambda: self._llm.generate_structured(prompt, **kwargs),+ model=kwargs.get("model"),)def generate_typed(self, prompt: str, schema, max_retries: int = 3, **kwargs):@@ -507,6 +536,7 @@ class OpenAILLMWithProvenance(LLMProvenanceMixin):prompt, schema, max_retries=max_retries, **kwargs),max_retries=max_retries,+ model=kwargs.get("model"),)def __getattr__(self, name):@@ -523,6 +553,11 @@ class HuggingFaceLLMWithProvenance(LLMProvenanceMixin):HuggingFace LLM with provenance tracking.Wraps the original HuggingFaceLLM and tracks all generations.++ The wrapped provider loads its model in its constructor and its+ ``generate`` reads only the generation options, so a per-call ``model``+ is forwarded and then ignored. Entries therefore record the constructor+ model, which is the one the call actually used (#2051)."""def __init__(@@ -671,6 +706,7 @@ class LiteLLMWithProvenance(LLMProvenanceMixin):e,start_time,activity_started_at_time,+ model=kwargs.get("model"),provider=kwargs.get("provider"),)raise@@ -706,6 +742,7 @@ class LiteLLMWithProvenance(LLMProvenanceMixin):latency_seconds=elapsed,activity_started_at_time=activity_started_at_time,activity_ended_at_time=activity_ended_at_time,+ model=kwargs.get("model"),provider=kwargs.get('provider'))@@ -718,6 +755,7 @@ class LiteLLMWithProvenance(LLMProvenanceMixin):"lite_structured",prompt,lambda: self._llm.generate_structured(prompt, **kwargs),+ model=kwargs.get("model"),)def generate_typed(self, prompt: str, schema, max_retries: int = 3, **kwargs):@@ -730,6 +768,7 @@ class LiteLLMWithProvenance(LLMProvenanceMixin):prompt, schema, max_retries=max_retries, **kwargs),max_retries=max_retries,+ model=kwargs.get("model"),)def __getattr__(self, name):diff --git a/tests/provenance/test_llms_provenance_tracking.py b/tests/provenance/test_llms_provenance_tracking.pyindex 620a22be..49cb4117 100644--- a/tests/provenance/test_llms_provenance_tracking.py+++ b/tests/provenance/test_llms_provenance_tracking.py@@ -1,18 +1,25 @@"""Regression tests for what the LLM provenance wrappers actually record.-Two gaps in the wrappers let calls go untracked or tracked without their-usage/cost:+Four gaps in the wrappers let calls go untracked, tracked without their+usage/cost, tracked under the wrong model, or not tracked at all:* ``generate_structured`` / ``generate_typed`` fell through ``__getattr__`` tothe wrapped LLM, so those calls produced no provenance entry at all.* ``generate`` read token counts and cost off the returned value, but theproviders returned a plain ``str``, so ``prompt_tokens`` / ``completion_tokens``/ ``total_cost`` were always ``None``.+* Every entry named the model the wrapper was constructed with, so a call that+ passed its own ``model=`` was recorded under a model it never used (#2051).+* A per-call ``model=`` that is not a string reached the metadata verbatim, so+ the storage layer could not serialize it: the write was rolled back and the+ entry was never stored (#2051).These tests drive the wrappers with a stub LLM and a recording provenancemanager so they stay offline and assert on the recorded metadata directly.-A second group drives the providers themselves with a canned client, so a-provider that stops carrying usage/cost turns the suite red.+One test drives a real ``ProvenanceManager`` over a sqlite file in ``tmp_path``+to prove the entry is really written, still offline. A second group drives the+providers themselves with a canned client, so a provider that stops carrying+usage/cost turns the suite red."""from types import SimpleNamespace@@ -22,14 +29,40 @@ from pydantic import BaseModelfrom semantica.llms.llms_provenance import (GroqLLMWithProvenance,+ HuggingFaceLLMWithProvenance,LiteLLMWithProvenance,+ OpenAILLMWithProvenance,)+from semantica.provenance import ProvenanceManagerfrom semantica.semantic_extract.providers import (GroqProvider,OpenAIProvider,ResponseText,)+_WRAPPER_CLASSES = {+ "GroqLLMWithProvenance": GroqLLMWithProvenance,+ "OpenAILLMWithProvenance": OpenAILLMWithProvenance,+ "HuggingFaceLLMWithProvenance": HuggingFaceLLMWithProvenance,+ "LiteLLMWithProvenance": LiteLLMWithProvenance,+}+_WRAPPER_NAMES = list(_WRAPPER_CLASSES)++# The HuggingFace provider loads its model in its constructor and its generate+# reads only the generation options, so a per-call ``model`` is ignored and the+# constructor model is the one the call actually used.+_HONOURS_PER_CALL_MODEL = {+ "GroqLLMWithProvenance": True,+ "OpenAILLMWithProvenance": True,+ "HuggingFaceLLMWithProvenance": False,+ "LiteLLMWithProvenance": True,+}+++def _expected_model(wrapper_name, per_call="per-call-model"):+ """The model an entry should name for *wrapper_name*."""+ return per_call if _HONOURS_PER_CALL_MODEL[wrapper_name] else "constructor-model"+class _RecordingProvenanceManager:"""Capture the kwargs of every ``track_entity`` call."""@@ -71,6 +104,38 @@ def _wrapper_with(llm):return wrapper, recorder+class _StubProvider:+ """Stand-in for the provider class a wrapper constructs."""++ def __init__(self, *args, **kwargs):+ pass+++def _wrapper_for(wrapper_name, monkeypatch, constructor_model="constructor-model"):+ """Build *wrapper_name* around a stub, with a known constructor model.++ Each wrapper imports the class it wraps lazily, inside ``__init__``, so+ the optional providers are stubbed here: the real HuggingFace provider+ loads a transformer model while constructing, and LiteLLM refuses to+ construct without the optional ``litellm`` package.+ """+ if wrapper_name == "HuggingFaceLLMWithProvenance":+ monkeypatch.setattr(+ "semantica.llms.huggingface.HuggingFaceLLMProvider", _StubProvider+ )+ if wrapper_name == "LiteLLMWithProvenance":+ monkeypatch.setattr("semantica.llms.litellm.LITELLM_AVAILABLE", True)++ wrapper = _WRAPPER_CLASSES[wrapper_name](provenance=False, model=constructor_model)+ recorder = _RecordingProvenanceManager()+ wrapper.provenance = True+ wrapper._prov_manager = recorder+ wrapper._llm = _StubLLM(+ response="answer", structured={"answer": 42}, typed="validated"+ )+ return wrapper, recorder++class TestStructuredAndTypedAreTracked:"""Structured/typed calls must produce a provenance entry."""@@ -428,3 +493,216 @@ def test_litellm_wrapper_reads_cost_from_response_text(monkeypatch):wrapper.generate("question")assert recorder.calls[0]["metadata"]["total_cost"] == 0.007+++class TestRecordedModelFollowsTheCall:+ """A recorded entry must name the model the call actually used (#2051)."""++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_per_call_model_is_recorded(self, wrapper_name, monkeypatch):+ """The entry names the model the call used, not the constructor's."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate("question", model="per-call-model")++ assert recorder.calls[0]["metadata"]["model"] == _expected_model(wrapper_name)++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_call_without_a_model_records_the_constructor_model(+ self, wrapper_name, monkeypatch+ ):+ """A call that names no model keeps the constructor's model."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate("question")++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_structured_path_records_the_per_call_model(+ self, wrapper_name, monkeypatch+ ):+ """The structured path reaches the recorder and names the same model."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate_structured("question", model="per-call-model")++ assert recorder.calls[0]["metadata"]["model"] == _expected_model(wrapper_name)++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_typed_path_records_the_per_call_model(self, wrapper_name, monkeypatch):+ """The typed path reaches the recorder and names the same model."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate_typed("question", schema=object, model="per-call-model")++ assert recorder.calls[0]["metadata"]["model"] == _expected_model(wrapper_name)++ def test_huggingface_records_the_model_its_provider_loaded(self, monkeypatch):+ """HF loads its model at construction, so a per-call value never runs."""+ wrapper, recorder = _wrapper_for("HuggingFaceLLMWithProvenance", monkeypatch)++ wrapper.generate("question", model="per-call-model")++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_none_model_falls_back_to_the_constructor_model(+ self, wrapper_name, monkeypatch+ ):+ """A per-call ``model=None`` names no model, so the constructor's is kept."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate("question", model=None)++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_empty_model_falls_back_to_the_constructor_model(+ self, wrapper_name, monkeypatch+ ):+ """An empty model name is not a model, so the constructor's is recorded."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate("question", model="")++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"++ def test_only_the_model_field_changes(self, monkeypatch):+ """No other recorded field may move when a per-call model is used."""+ wrapper, recorder = _wrapper_for("GroqLLMWithProvenance", monkeypatch)++ wrapper.generate("question")+ wrapper.generate("question", model="per-call-model")++ first, second = (call["metadata"] for call in recorder.calls)+ assert first["model"] == "constructor-model"+ assert second["model"] == "per-call-model"+ # The model is the one field that must differ; the latency moves on+ # its own between any two calls.+ ignored = {"model", "latency_seconds"}+ assert {k: v for k, v in first.items() if k not in ignored} == {+ k: v for k, v in second.items() if k not in ignored+ }+++class TestTheRecorderResolvesTheModel:+ """The shared recorder, not the call sites, decides what is recorded."""++ def test_the_recorder_records_the_model_it_is_handed(self, monkeypatch):+ """A direct recorder call records the model it was given."""+ wrapper, recorder = _wrapper_for("GroqLLMWithProvenance", monkeypatch)++ wrapper._track_llm_call(+ call_id="c1", prompt="p", response="r", model="direct-model"+ )++ assert recorder.calls[0]["metadata"]["model"] == "direct-model"++ @pytest.mark.parametrize(+ "model",+ [None, "", " "],+ ids=["none", "empty", "whitespace"],+ )+ def test_the_recorder_falls_back_for_a_value_that_names_no_model(+ self, model, monkeypatch+ ):+ """The recorder itself falls back; the call sites do not decide."""+ wrapper, recorder = _wrapper_for("GroqLLMWithProvenance", monkeypatch)++ wrapper._track_llm_call(call_id="c2", prompt="p", response="r", model=model)++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"++ def test_the_recorder_falls_back_for_a_value_that_is_not_a_string(+ self, monkeypatch+ ):+ """A model that is not a string never reaches the recorded metadata."""+ wrapper, recorder = _wrapper_for("GroqLLMWithProvenance", monkeypatch)++ wrapper._track_llm_call(call_id="c3", prompt="p", response="r", model=object())++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"+++class TestAModelThatNamesNoModelFallsBack:+ """A per-call model that names no model never becomes the recorded one."""++ @pytest.mark.parametrize(+ "model",+ [None, "", " ", 0, False, object()],+ ids=["none", "empty", "whitespace", "zero", "false", "object"],+ )+ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_a_value_that_names_no_model_falls_back(+ self, wrapper_name, model, monkeypatch+ ):+ """Every value that names no model records the constructor's model."""+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)++ wrapper.generate("question", model=model)++ recorded = recorder.calls[0]["metadata"]["model"]+ assert recorded == "constructor-model"+ assert isinstance(recorded, str)++ def test_a_non_string_model_never_reaches_the_metadata(self, monkeypatch):+ """The raw value is dropped, so nothing unserializable is recorded."""+ wrapper, recorder = _wrapper_for("GroqLLMWithProvenance", monkeypatch)+ unserializable = object()++ wrapper.generate("question", model=unserializable)++ metadata = recorder.calls[0]["metadata"]+ assert metadata["model"] == "constructor-model"+ assert unserializable not in metadata.values()++ def test_a_non_serializable_model_still_writes_the_entry(self, tmp_path):+ """The entry survives a model the storage layer cannot serialize."""+ wrapper = GroqLLMWithProvenance(provenance=False, model="constructor-model")+ manager = ProvenanceManager(storage_path=str(tmp_path / "provenance.db"))+ wrapper.provenance = True+ wrapper._prov_manager = manager+ wrapper._llm = _StubLLM(response="answer")++ wrapper.generate("question", model=object())++ stored = manager.storage.retrieve_all(entity_type="llm_generation")+ assert len(stored) == 1+ assert stored[0].metadata["model"] == "constructor-model"+++class _RaisingLLM(_StubLLM):+ """A stub whose generation entry points raise, to drive the failure path."""++ def generate(self, prompt, **kwargs):+ raise RuntimeError("provider failed")+++class TestFailedCallsRecordTheModelTheyWereGiven:+ """A failed call names the model it asked for, not the constructor's."""++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_failed_generate_records_the_per_call_model(+ self, wrapper_name, monkeypatch+ ):+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)+ wrapper._llm = _RaisingLLM()++ with pytest.raises(RuntimeError):+ wrapper.generate("question", model="per-call-model")++ assert recorder.calls, "no entry was recorded for the failed call"+ assert recorder.calls[0]["metadata"]["model"] == _expected_model(wrapper_name)++ @pytest.mark.parametrize("wrapper_name", _WRAPPER_NAMES)+ def test_failed_generate_without_a_model_keeps_the_constructor_model(+ self, wrapper_name, monkeypatch+ ):+ wrapper, recorder = _wrapper_for(wrapper_name, monkeypatch)+ wrapper._llm = _RaisingLLM()++ with pytest.raises(RuntimeError):+ wrapper.generate("question")++ assert recorder.calls[0]["metadata"]["model"] == "constructor-model"