loopgate-research 0.2.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.
src/evaluation.py ADDED
@@ -0,0 +1,281 @@
1
+ """Repeatable offline research-quality evaluation using labeled graph fixtures."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import re
9
+ from dataclasses import dataclass
10
+ from types import SimpleNamespace
11
+ from typing import Any
12
+ from unittest.mock import patch
13
+
14
+ from src.config import get_settings
15
+ from src.pipeline import PipelineRunner
16
+
17
+ _CITATION_PATTERN = re.compile(r"\[(\d+)\]")
18
+ _REQUIRED_SECTIONS = (
19
+ "### Technical Telemetry",
20
+ "### Core Narrative",
21
+ "### Extracted Key Metrics",
22
+ "### Sources",
23
+ )
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class EvaluationCase:
28
+ """One labeled research case with claims tied to source IDs."""
29
+
30
+ name: str
31
+ topic: str
32
+ sources: tuple[dict[str, str], ...]
33
+ claims: tuple[tuple[int, str], ...]
34
+ mode: str = "valid"
35
+
36
+ @property
37
+ def expects_fallback(self) -> bool:
38
+ return self.mode != "valid"
39
+
40
+ @property
41
+ def fallback_reason(self) -> str | None:
42
+ return {
43
+ "valid": None,
44
+ "invalid": "invalid_model_output",
45
+ "error": "openai_error",
46
+ "unconfigured": "openai_not_configured",
47
+ }[self.mode]
48
+
49
+ def model_digest(self) -> str:
50
+ claims = " ".join(f"{claim} [{source_id}]" for source_id, claim in self.claims)
51
+ return (
52
+ f"### Technical Telemetry\n{claims}\n\n"
53
+ f"### Core Narrative\nThe digest preserves labeled evidence: {claims}\n\n"
54
+ f"### Extracted Key Metrics\n- Labeled claims: {len(self.claims)}"
55
+ )
56
+
57
+
58
+ def _sources(topic: str, first: str, second: str) -> tuple[dict[str, str], ...]:
59
+ slug = topic.lower().replace(" ", "-")
60
+ return (
61
+ {
62
+ "title": f"{topic} measurements",
63
+ "url": f"https://research.test/{slug}",
64
+ "content": f"The primary study reports {first}.",
65
+ },
66
+ {
67
+ "title": f"{topic} operations",
68
+ "url": f"https://engineering.test/{slug}",
69
+ "content": f"The operational review reports {second}.",
70
+ },
71
+ {
72
+ "title": f"{topic} corroboration",
73
+ "url": f"https://research.test/{slug}/corroboration",
74
+ "content": f"Independent analysis corroborates {first} and {second}.",
75
+ },
76
+ )
77
+
78
+
79
+ EVALUATION_CASES = (
80
+ EvaluationCase(
81
+ name="valid_model_synthesis",
82
+ topic="kernel telemetry improvements",
83
+ sources=_sources("kernel telemetry", "12% higher throughput", "30 seconds of latency"),
84
+ claims=((1, "12% higher throughput"), (2, "30 seconds of latency")),
85
+ ),
86
+ EvaluationCase(
87
+ name="invalid_citation_fallback",
88
+ topic="checkpointed agent pipelines",
89
+ sources=_sources("checkpointed agents", "99.9% successful resumes", "five search steps"),
90
+ claims=((1, "99.9% successful resumes"), (2, "five search steps")),
91
+ mode="invalid",
92
+ ),
93
+ EvaluationCase(
94
+ name="provider_error_fallback",
95
+ topic="local source ranking",
96
+ sources=_sources("local ranking", "20% better precision", "ten retrieved candidates"),
97
+ claims=((1, "20% better precision"), (2, "ten retrieved candidates")),
98
+ mode="error",
99
+ ),
100
+ EvaluationCase(
101
+ name="unconfigured_model_fallback",
102
+ topic="human review workflows",
103
+ sources=_sources("human review", "two approval decisions", "zero silent truncations"),
104
+ claims=((1, "two approval decisions"), (2, "zero silent truncations")),
105
+ mode="unconfigured",
106
+ ),
107
+ )
108
+
109
+
110
+ def score_digest(
111
+ *,
112
+ digest: str,
113
+ raw_data: list[dict[str, Any]],
114
+ coverage_report: dict[str, Any],
115
+ extracted_metrics: dict[str, Any],
116
+ claims: tuple[tuple[int, str], ...],
117
+ expects_fallback: bool,
118
+ fallback_reason: str | None,
119
+ ) -> dict[str, float]:
120
+ """Score deterministic citation, coverage, claim-support, and fallback checks."""
121
+ body, separator, manifest = digest.partition("### Sources")
122
+ citations = [int(value) for value in _CITATION_PATTERN.findall(body)]
123
+ valid_citations = sum(1 <= citation <= len(raw_data) for citation in citations)
124
+ citation_score = valid_citations / len(citations) if citations else 0.0
125
+ manifest_valid = bool(separator) and all(
126
+ f"[{index}]" in manifest and str(source.get("url")) in manifest
127
+ for index, source in enumerate(raw_data, start=1)
128
+ )
129
+ if not manifest_valid:
130
+ citation_score = 0.0
131
+
132
+ domains = {
133
+ str(source.get("url", "")).split("/")[2]
134
+ for source in raw_data
135
+ if str(source.get("url", "")).startswith(("http://", "https://"))
136
+ }
137
+ coverage_score = (
138
+ min(len(raw_data) / 3, 1.0) + min(len(domains) / 2, 1.0)
139
+ ) / 2
140
+ if coverage_report.get("continue_research"):
141
+ coverage_score = 0.0
142
+
143
+ supported_claims = 0
144
+ for source_id, claim in claims:
145
+ if not 1 <= source_id <= len(raw_data):
146
+ continue
147
+ source_text = str(raw_data[source_id - 1].get("content", ""))
148
+ if claim in source_text and claim in body and f"[{source_id}]" in body:
149
+ supported_claims += 1
150
+ factual_score = supported_claims / len(claims) if claims else 0.0
151
+
152
+ if expects_fallback:
153
+ fallback_checks = (
154
+ extracted_metrics.get("llm_synthesis") is False,
155
+ extracted_metrics.get("fallback_reason") == fallback_reason,
156
+ "# Digest (no-LLM fallback)" in digest,
157
+ all(section in digest for section in _REQUIRED_SECTIONS),
158
+ bool(raw_data)
159
+ and str(raw_data[0].get("content", ""))[:100] in digest,
160
+ )
161
+ else:
162
+ fallback_checks = (
163
+ extracted_metrics.get("llm_synthesis") is True,
164
+ extracted_metrics.get("fallback_reason") is None,
165
+ "# Digest (no-LLM fallback)" not in digest,
166
+ all(section in digest for section in _REQUIRED_SECTIONS),
167
+ )
168
+ fallback_score = sum(fallback_checks) / len(fallback_checks)
169
+ scores = {
170
+ "citation_accuracy": round(citation_score, 4),
171
+ "coverage": round(coverage_score, 4),
172
+ "factual_consistency": round(factual_score, 4),
173
+ "fallback_quality": round(fallback_score, 4),
174
+ }
175
+ scores["overall"] = round(sum(scores.values()) / len(scores), 4)
176
+ return scores
177
+
178
+
179
+ class _EvaluationTavilyClient:
180
+ sources: tuple[dict[str, str], ...] = ()
181
+
182
+ def __init__(self, api_key: str | None = None) -> None:
183
+ pass
184
+
185
+ def search(self, **_: object) -> dict[str, Any]:
186
+ return {"results": [dict(source) for source in type(self).sources]}
187
+
188
+
189
+ class _EvaluationChatOpenAI:
190
+ mode = "valid"
191
+ digest = ""
192
+
193
+ def __init__(self, **_: object) -> None:
194
+ pass
195
+
196
+ async def ainvoke(self, prompt: str) -> SimpleNamespace:
197
+ if "research planning agent" in prompt:
198
+ return SimpleNamespace(content=json.dumps({"queries": ["labeled evidence"]}))
199
+ if type(self).mode == "error":
200
+ raise RuntimeError("intentional evaluation provider failure")
201
+ if type(self).mode == "invalid":
202
+ return SimpleNamespace(content="### Technical Telemetry\nInvalid [99]")
203
+ return SimpleNamespace(content=type(self).digest)
204
+
205
+
206
+ async def _run_case(case: EvaluationCase) -> dict[str, Any]:
207
+ _EvaluationTavilyClient.sources = case.sources
208
+ _EvaluationChatOpenAI.mode = case.mode
209
+ _EvaluationChatOpenAI.digest = case.model_digest()
210
+ settings = SimpleNamespace(
211
+ tavily_api_key="evaluation-tavily",
212
+ openai_api_key=None if case.mode == "unconfigured" else "evaluation-openai",
213
+ openai_model="evaluation-model",
214
+ ollama_base_url=None,
215
+ ollama_model=None,
216
+ max_research_steps=2,
217
+ local_ranking_enabled=False,
218
+ )
219
+ runner = PipelineRunner()
220
+ try:
221
+ with patch("src.graph.nodes.get_settings", return_value=settings), patch(
222
+ "src.graph.nodes.TavilyClient", _EvaluationTavilyClient
223
+ ), patch("src.graph.nodes.ChatOpenAI", _EvaluationChatOpenAI):
224
+ status = await runner.start(case.topic, thread_id=f"evaluation-{case.name}")
225
+ finally:
226
+ await runner.aclose()
227
+
228
+ scores = score_digest(
229
+ digest=status.digest,
230
+ raw_data=status.values["raw_data"],
231
+ coverage_report=status.values["coverage_report"],
232
+ extracted_metrics=status.values["extracted_metrics"],
233
+ claims=case.claims,
234
+ expects_fallback=case.expects_fallback,
235
+ fallback_reason=case.fallback_reason,
236
+ )
237
+ passed = status.is_pending and all(
238
+ score == 1.0 for name, score in scores.items() if name != "overall"
239
+ )
240
+ return {
241
+ "name": case.name,
242
+ "topic": case.topic,
243
+ "mode": case.mode,
244
+ "scores": scores,
245
+ "passed": passed,
246
+ "provider_telemetry": status.values["provider_telemetry"],
247
+ }
248
+
249
+
250
+ async def run_evaluation() -> dict[str, Any]:
251
+ """Run all labeled cases offline and return a JSON-serializable report."""
252
+ with patch.dict(os.environ, {"LOOPGATE_CHECKPOINT_DB": ""}):
253
+ get_settings.cache_clear()
254
+ try:
255
+ results = [await _run_case(case) for case in EVALUATION_CASES]
256
+ finally:
257
+ get_settings.cache_clear()
258
+ metric_names = ("citation_accuracy", "coverage", "factual_consistency", "fallback_quality", "overall")
259
+ summary = {
260
+ name: round(sum(case["scores"][name] for case in results) / len(results), 4)
261
+ for name in metric_names
262
+ }
263
+ return {
264
+ "evaluation_version": 1,
265
+ "mode": "offline_labeled_fixtures",
266
+ "case_count": len(results),
267
+ "all_passed": all(case["passed"] for case in results),
268
+ "summary": summary,
269
+ "cases": results,
270
+ }
271
+
272
+
273
+ def main() -> int:
274
+ """Print the deterministic faculty/report-friendly JSON evaluation."""
275
+ report = asyncio.run(run_evaluation())
276
+ print(json.dumps(report, indent=2))
277
+ return 0 if report["all_passed"] else 1
278
+
279
+
280
+ if __name__ == "__main__":
281
+ raise SystemExit(main())
src/graph/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Graph primitives for loopgate."""
2
+
3
+ from src.graph.graph import assemble_graph, build_graph
4
+ from src.graph.state import ApprovalStatus, GraphState
5
+
6
+ __all__ = ["GraphState", "ApprovalStatus", "build_graph", "assemble_graph"]
src/graph/graph.py ADDED
@@ -0,0 +1,90 @@
1
+ """Graph assembly for the loopgate human-in-the-loop pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ from langgraph.checkpoint.base import BaseCheckpointSaver
8
+ from langgraph.checkpoint.memory import MemorySaver
9
+ from langgraph.graph import END, START, StateGraph
10
+
11
+ from src.graph.nodes import (
12
+ digest_compiler_node,
13
+ evidence_review_node,
14
+ failure_node,
15
+ finalize_node,
16
+ research_node,
17
+ research_planner_node,
18
+ review_gate_node,
19
+ route_after_compilation,
20
+ route_after_evidence_review,
21
+ route_after_review,
22
+ )
23
+ from src.graph.state import GraphState
24
+
25
+ REVIEW_NODE: Final = "review_gate"
26
+ FAILURE_NODE: Final = "failure"
27
+ DEFAULT_INTERRUPT_BEFORE: Final[tuple[str, ...]] = (REVIEW_NODE,)
28
+
29
+
30
+ def build_graph(
31
+ checkpointer: BaseCheckpointSaver | None = None, *, interrupt_before=None
32
+ ):
33
+ """Compile the research graph with a checkpointed review gate.
34
+
35
+ Execution order::
36
+
37
+ START -> planner -> researcher -> evidence_review -> compiler
38
+ ^ │ │
39
+ └───────────────┘ │
40
+ [INTERRUPT] review_gate
41
+ │
42
+ finalize
43
+ Research and compilation failures route through failure to END before review.
44
+
45
+ The graph halts *before* ``review_gate``. A caller can inspect the compiled
46
+ digest, persist a decision with ``aupdate_state``, then resume with
47
+ ``ainvoke(None, config=...)``.
48
+ """
49
+ workflow = StateGraph(GraphState)
50
+
51
+ workflow.add_node("planner", research_planner_node)
52
+ workflow.add_node("researcher", research_node)
53
+ workflow.add_node("evidence_review", evidence_review_node)
54
+ workflow.add_node("compiler", digest_compiler_node)
55
+ workflow.add_node(FAILURE_NODE, failure_node)
56
+ workflow.add_node(REVIEW_NODE, review_gate_node)
57
+ workflow.add_node("finalize", finalize_node)
58
+
59
+ workflow.add_edge(START, "planner")
60
+ workflow.add_edge("planner", "researcher")
61
+ workflow.add_edge("researcher", "evidence_review")
62
+ workflow.add_conditional_edges(
63
+ "evidence_review",
64
+ route_after_evidence_review,
65
+ {"research": "researcher", "compile": "compiler"},
66
+ )
67
+ workflow.add_conditional_edges(
68
+ "compiler",
69
+ route_after_compilation,
70
+ {"review": REVIEW_NODE, "failed": FAILURE_NODE},
71
+ )
72
+ workflow.add_edge(FAILURE_NODE, END)
73
+ workflow.add_conditional_edges(
74
+ REVIEW_NODE,
75
+ route_after_review,
76
+ {"finalize": "finalize", "end": END},
77
+ )
78
+ workflow.add_edge("finalize", END)
79
+
80
+ if interrupt_before is None:
81
+ interrupt_before = DEFAULT_INTERRUPT_BEFORE
82
+
83
+ return workflow.compile(
84
+ checkpointer=checkpointer or MemorySaver(),
85
+ interrupt_before=list(interrupt_before),
86
+ )
87
+
88
+
89
+ # Backwards-compatible name used by the original scaffold.
90
+ assemble_graph = build_graph