contextgate-core 0.6.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,165 @@
1
+ """
2
+ HuggingFace Downstream Agent Consumer (`app.py`)
3
+ ================================================
4
+ Consumes `CompiledPrompt` from `pipeline.py` and supports side-by-side A/B evaluation
5
+ of Raw vs. Deterministically Optimized prompts against HuggingFace Inference API
6
+ (or any OpenAI-compatible local/remote endpoint), with an offline deterministic
7
+ simulation mode when `HF_TOKEN` is not set.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import dataclasses
13
+ import json
14
+ import os
15
+ import time
16
+ import urllib.error
17
+ import urllib.request
18
+ from typing import Any
19
+
20
+ from .data_contracts import RawRequest
21
+ from .pipeline import audit_agent_response, estimate_tokens, optimize
22
+
23
+ DEFAULT_HF_MODEL = os.environ.get("HF_MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
24
+ DEFAULT_HF_API_URL = os.environ.get(
25
+ "HF_API_URL",
26
+ f"https://router.huggingface.co/hf-inference/models/{DEFAULT_HF_MODEL}/v1/chat/completions",
27
+ )
28
+
29
+
30
+ def call_huggingface_llm(
31
+ prompt_text: str,
32
+ model_id: str | None = None,
33
+ max_new_tokens: int = 350,
34
+ temperature: float = 0.1,
35
+ ) -> tuple[str, float, str]:
36
+ """
37
+ Calls HuggingFace Inference API (via `huggingface_hub.InferenceClient` if installed,
38
+ or standard-library `urllib.request`) and returns (response_text, latency_ms, backend_used).
39
+ Falls back to a deterministic offline evaluator if `HF_TOKEN` is not configured.
40
+ """
41
+ t0 = time.perf_counter()
42
+ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN", "")
43
+ target_model = model_id or DEFAULT_HF_MODEL
44
+
45
+ if hf_token:
46
+ # 1. Try huggingface_hub.InferenceClient if installed in user's venv
47
+ try:
48
+ from huggingface_hub import InferenceClient # type: ignore
49
+ client = InferenceClient(model=target_model, token=hf_token)
50
+ res = client.chat_completion(
51
+ messages=[{"role": "user", "content": prompt_text}],
52
+ max_tokens=max_new_tokens,
53
+ temperature=temperature,
54
+ )
55
+ content = res.choices[0].message.content or ""
56
+ latency = round((time.perf_counter() - t0) * 1000, 2)
57
+ return content.strip(), latency, f"huggingface_hub ({target_model})"
58
+ except ImportError:
59
+ pass
60
+ except Exception as exc:
61
+ latency = round((time.perf_counter() - t0) * 1000, 2)
62
+ return f"[HF API Error: {exc}]", latency, f"huggingface_hub_error ({target_model})"
63
+
64
+ # 2. Zero-dependency HTTP fallback via urllib.request
65
+ try:
66
+ req_body = json.dumps({
67
+ "model": target_model,
68
+ "messages": [{"role": "user", "content": prompt_text}],
69
+ "max_tokens": max_new_tokens,
70
+ "temperature": temperature,
71
+ }).encode("utf-8")
72
+ req = urllib.request.Request(
73
+ DEFAULT_HF_API_URL,
74
+ data=req_body,
75
+ headers={
76
+ "Authorization": f"Bearer {hf_token}",
77
+ "Content-Type": "application/json",
78
+ },
79
+ method="POST",
80
+ )
81
+ with urllib.request.urlopen(req, timeout=30) as resp:
82
+ data = json.loads(resp.read().decode("utf-8"))
83
+ content = data["choices"][0]["message"]["content"]
84
+ latency = round((time.perf_counter() - t0) * 1000, 2)
85
+ return content.strip(), latency, f"hf_http_router ({target_model})"
86
+ except Exception as exc:
87
+ latency = round((time.perf_counter() - t0) * 1000, 2)
88
+ return f"[HF HTTP Error: {exc}]", latency, f"hf_http_error ({target_model})"
89
+
90
+ # 3. Offline local simulation when HF_TOKEN is not set (so UI/CLI testing always works)
91
+ is_compiled_xml = "<agent_instructions>" in prompt_text and "<core_task>" in prompt_text
92
+ if is_compiled_xml:
93
+ sim_output = (
94
+ "```python\n"
95
+ "def reverse_string(s: str) -> str:\n"
96
+ " # Complies with <task_metadata> negation: without using slicing\n"
97
+ " chars = []\n"
98
+ " for idx in range(len(s) - 1, -1, -1):\n"
99
+ " chars.append(s[idx])\n"
100
+ " return ''.join(chars)\n"
101
+ "```"
102
+ )
103
+ else:
104
+ sim_output = (
105
+ "Sure! Here is a quick Python function to reverse a string:\n"
106
+ "def reverse_string(s):\n"
107
+ " return s[::-1] # Note: unoptimized prompt often defaults to [::-1] slicing!"
108
+ )
109
+ latency = round((time.perf_counter() - t0) * 1000, 2)
110
+ return sim_output, latency, "offline_simulator (set HF_TOKEN for live HuggingFace API)"
111
+
112
+
113
+ def compare_raw_vs_optimized(request: RawRequest, model_id: str | None = None) -> dict[str, Any]:
114
+ """
115
+ Runs a side-by-side A/B comparison:
116
+ - Call A: Raw unoptimized prompt + unpruned context chunks
117
+ - Call B: Deterministically compiled XML prompt (`CompiledPrompt.payload`)
118
+ Audits both responses using `audit_agent_response()` from `pipeline.py`.
119
+ """
120
+ compiled = optimize(request)
121
+ if compiled.status != "OK":
122
+ return {
123
+ "status": compiled.status,
124
+ "clarification_request": compiled.clarification_request,
125
+ "trace": dataclasses.asdict(compiled.trace),
126
+ }
127
+
128
+ # Build the unoptimized raw input (what a naive agent sends without NLP-Smarty)
129
+ raw_parts = []
130
+ if request.conversation_history:
131
+ hist_str = "\n".join(f"{t.get('role', 'user')}: {t.get('content', '')}" for t in request.conversation_history)
132
+ raw_parts.append(f"Conversation History:\n{hist_str}")
133
+ if request.context_chunks:
134
+ raw_parts.append("Context:\n" + "\n\n".join(request.context_chunks))
135
+ raw_parts.append(request.text)
136
+ unoptimized_input = "\n\n".join(raw_parts)
137
+
138
+ raw_answer, raw_llm_ms, backend = call_huggingface_llm(unoptimized_input, model_id=model_id)
139
+ opt_answer, opt_llm_ms, _ = call_huggingface_llm(compiled.payload, model_id=model_id)
140
+
141
+ raw_audit = audit_agent_response(raw_answer, compiled.trace)
142
+ opt_audit = audit_agent_response(opt_answer, compiled.trace)
143
+
144
+ return {
145
+ "status": "OK",
146
+ "backend": backend,
147
+ "raw_input_tokens": estimate_tokens(unoptimized_input),
148
+ "optimized_input_tokens": compiled.trace.compiled_payload_token_count,
149
+ "raw_response": raw_answer,
150
+ "raw_llm_latency_ms": raw_llm_ms,
151
+ "raw_audit": raw_audit,
152
+ "optimized_payload": compiled.payload,
153
+ "optimized_response": opt_answer,
154
+ "optimized_llm_latency_ms": opt_llm_ms,
155
+ "optimized_audit": opt_audit,
156
+ "trace": dataclasses.asdict(compiled.trace),
157
+ }
158
+
159
+
160
+ if __name__ == "__main__":
161
+ sample_req = RawRequest(
162
+ text="Could you please help me write a Python function to reverse a string without using slicing?"
163
+ )
164
+ comparison = compare_raw_vs_optimized(sample_req)
165
+ print(json.dumps(comparison, indent=2))
@@ -0,0 +1,173 @@
1
+ """
2
+ Deterministic retrieval evaluation from git history (replaces unmeasured token-savings claims).
3
+
4
+ For each recent non-merge commit C touching indexable files:
5
+ * query = C's commit message (subject + body)
6
+ * ground truth = indexable files changed by C
7
+ * repo state = C's PARENT tree (exported to a temp dir), so the index never sees the answer
8
+ Metrics: file recall@k (k=1,3,5), hit-rate@5, capsule tokens, and token cost vs. two baselines:
9
+ - "read changed files" : raw tokens of the ground-truth files (optimistic baseline: agent knows where to look)
10
+ - "read all candidates": raw tokens of every file in the repo index (pessimistic blind-exploration baseline)
11
+ Commit messages are a noisy proxy for a real task; treat results as relative signal (regression gate), not truth.
12
+
13
+ Usage: python eval_retrieval.py [--root .] [-n 20] [--json out.json] [--min-recall5 0.0]
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ import tarfile
24
+ import tempfile
25
+ from typing import Any
26
+
27
+ from . import repo_indexer as ri
28
+
29
+
30
+ def _git(root: str, *args: str) -> str:
31
+ p = subprocess.run(["git", "-C", root, *args], capture_output=True, text=True, timeout=60)
32
+ if p.returncode != 0:
33
+ raise RuntimeError(p.stderr.strip() or f"git {' '.join(args)} failed")
34
+ return p.stdout
35
+
36
+
37
+ def list_commits(root: str, n: int) -> list[str]:
38
+ return _git(root, "rev-list", "--no-merges", "--max-parents=1", f"--max-count={n * 3}", "HEAD").split()
39
+
40
+
41
+ def _export_tree(root: str, rev: str, dest: str) -> None:
42
+ p = subprocess.run(["git", "-C", root, "archive", "--format=tar", rev], capture_output=True, timeout=120)
43
+ if p.returncode != 0:
44
+ raise RuntimeError(p.stderr.decode(errors="replace"))
45
+ import io
46
+
47
+ with tarfile.open(fileobj=io.BytesIO(p.stdout)) as tf:
48
+ for m in tf.getmembers(): # path-traversal guard
49
+ if m.name.startswith("/") or ".." in m.name.split("/"):
50
+ continue
51
+ tf.extract(m, dest)
52
+
53
+
54
+ def _indexable(path: str) -> bool:
55
+ parts = path.split("/")
56
+ return (os.path.splitext(path)[1].lower() in ri.LANG_BY_EXT and not any(p in ri.IGNORE_DIRS for p in parts[:-1])
57
+ and parts[-1] not in ri.IGNORE_FILES)
58
+
59
+
60
+ def evaluate(root: str, n: int = 20, budget: int = 450, k: int = 5) -> dict[str, Any]:
61
+ root = os.path.abspath(root)
62
+ cases: list[dict[str, Any]] = []
63
+ for rev in list_commits(root, n):
64
+ if len(cases) >= n:
65
+ break
66
+ msg = _git(root, "log", "-1", "--format=%B", rev).strip()
67
+ changed = [f for f in _git(root, "diff-tree", "--no-commit-id", "--name-only", "-r", "--diff-filter=AM", rev).split("\n")
68
+ if f and _indexable(f)]
69
+ if not msg or not changed:
70
+ continue
71
+ with tempfile.TemporaryDirectory() as tmp:
72
+ try:
73
+ _export_tree(root, f"{rev}^", tmp)
74
+ except RuntimeError:
75
+ continue # root commit
76
+ con = ri._connect(tmp)
77
+ ri.refresh(tmp, con)
78
+ existing = {r["path"]: r["tokens_raw"] for r in con.execute("SELECT path, tokens_raw FROM files")}
79
+ truth = [f for f in changed if f in existing] # files added by C cannot be retrieved from the parent
80
+ if not truth:
81
+ con.close()
82
+ continue
83
+ res = ri.search(tmp, msg, k=k, recency=False, con=con, auto_refresh=False)
84
+ con.close()
85
+ ranked_files: list[str] = []
86
+ for h in res["hits"]:
87
+ if h["path"] not in ranked_files:
88
+ ranked_files.append(h["path"])
89
+ cap = ri.build_capsule(tmp, msg, token_budget=budget, k=k)
90
+ cases.append({
91
+ "commit": rev[:8], "subject": msg.split("\n")[0][:70], "truth": truth, "retrieved": ranked_files,
92
+ "recall@1": len(set(ranked_files[:1]) & set(truth)) / len(truth),
93
+ "recall@3": len(set(ranked_files[:3]) & set(truth)) / len(truth),
94
+ "recall@5": len(set(ranked_files[:5]) & set(truth)) / len(truth),
95
+ "hit@5": bool(set(ranked_files[:5]) & set(truth)),
96
+ "capsule_tokens": cap["tokens"], "capsule_reason": cap["reason"],
97
+ "baseline_changed_tokens": sum(existing[f] for f in truth),
98
+ "baseline_all_tokens": sum(existing.values()),
99
+ })
100
+ return {"cases": cases, "summary": _summarize(cases)}
101
+
102
+
103
+ def evaluate_golden(root: str, path: str | None = None, k: int = 5) -> dict[str, Any]:
104
+ """Hand-labelled task -> symbol queries (tests/golden_queries.json). Metrics: recall@k, top-1, gate emit rate."""
105
+ root = os.path.abspath(root)
106
+ path = path or os.path.join(root, "tests", "golden_queries.json")
107
+ cases = json.load(open(path))
108
+ ri.refresh(root)
109
+ rows = []
110
+ for c in cases:
111
+ got = [f"{h['path']}:{h['name']}" for h in ri.search(root, c["q"], k=k, recency=False)["hits"]]
112
+ exp = set(c["expect"])
113
+ rows.append({"q": c["q"], "set": c.get("set", "dev"), "recall@k": bool(exp & set(got)),
114
+ "top1": bool(got and got[0] in exp), "emit": ri.build_capsule(root, c["q"])["reason"] == "ok",
115
+ "got": got[:3]})
116
+ def agg(rs):
117
+ n = len(rs) or 1
118
+ return {"n": len(rs), f"recall@{k}": round(sum(r["recall@k"] for r in rs) / n, 3),
119
+ "top1": round(sum(r["top1"] for r in rs) / n, 3), "emit_rate": round(sum(r["emit"] for r in rs) / n, 3)}
120
+ return {"all": agg(rows), "dev": agg([r for r in rows if r["set"] == "dev"]),
121
+ "heldout": agg([r for r in rows if r["set"] == "heldout"]), "rows": rows}
122
+
123
+
124
+ def _summarize(cases: list[dict]) -> dict[str, Any]:
125
+ if not cases:
126
+ return {"n": 0}
127
+ m = lambda key: sum(c[key] for c in cases) / len(cases) # noqa: E731
128
+ emitted = [c for c in cases if c["capsule_reason"] == "ok"]
129
+ e_cap = sum(c["capsule_tokens"] for c in emitted)
130
+ e_chg = sum(c["baseline_changed_tokens"] for c in emitted)
131
+ e_all = sum(c["baseline_all_tokens"] for c in emitted)
132
+ return {
133
+ "n": len(cases),
134
+ "recall@1": round(m("recall@1"), 3), "recall@3": round(m("recall@3"), 3), "recall@5": round(m("recall@5"), 3),
135
+ "hit_rate@5": round(sum(c["hit@5"] for c in cases) / len(cases), 3),
136
+ "capsule_emitted_rate": round(len(emitted) / len(cases), 3),
137
+ "n_emitted": len(emitted),
138
+ "avg_capsule_tokens_emitted": round(e_cap / len(emitted), 1) if emitted else 0,
139
+ # savings are computed ONLY over cases where a capsule was actually emitted (empty capsules save nothing useful)
140
+ "emitted_vs_changed_files_pct": round(100 * (1 - e_cap / e_chg), 1) if e_chg else None,
141
+ "emitted_vs_all_files_pct": round(100 * (1 - e_cap / e_all), 1) if e_all else None,
142
+ }
143
+
144
+
145
+ def main(argv: list[str] | None = None) -> int:
146
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[1])
147
+ ap.add_argument("--root", default=".")
148
+ ap.add_argument("-n", type=int, default=20)
149
+ ap.add_argument("--budget", type=int, default=450)
150
+ ap.add_argument("--json", dest="json_out")
151
+ ap.add_argument("--golden", action="store_true", help="evaluate tests/golden_queries.json instead of git history")
152
+ ap.add_argument("--min-recall5", type=float, default=0.0, help="exit 1 if mean recall@5 is below this (CI gate)")
153
+ a = ap.parse_args(argv)
154
+ if a.golden:
155
+ g = evaluate_golden(a.root)
156
+ for r in g["rows"]:
157
+ print(f"{'OK ' if r['recall@k'] else 'MISS'} {'top1' if r['top1'] else ' '} {'emit' if r['emit'] else ' '} "
158
+ f"[{r['set']}] {r['q'][:60]} -> {r['got'][:2]}")
159
+ print(json.dumps({k: v for k, v in g.items() if k != "rows"}, indent=2))
160
+ return 1 if g["all"]["recall@5"] < a.min_recall5 else 0
161
+ out = evaluate(a.root, a.n, a.budget)
162
+ for c in out["cases"]:
163
+ print(f"{c['commit']} r@1={c['recall@1']:.2f} r@5={c['recall@5']:.2f} cap={c['capsule_tokens']:>4}t "
164
+ f"[{c['capsule_reason']}] {c['subject']}")
165
+ print(json.dumps(out["summary"], indent=2))
166
+ if a.json_out:
167
+ with open(a.json_out, "w") as f:
168
+ json.dump(out, f, indent=2)
169
+ return 1 if out["summary"].get("n", 0) and out["summary"]["recall@5"] < a.min_recall5 else 0
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())