local-context-compiler 0.4.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.
- lcc/__init__.py +72 -0
- lcc/agents/__init__.py +37 -0
- lcc/agents/local_agent.py +403 -0
- lcc/agents/local_solver.py +89 -0
- lcc/agents/local_verifier.py +276 -0
- lcc/benchmarking/__init__.py +65 -0
- lcc/benchmarking/case_loader.py +257 -0
- lcc/benchmarking/metadata.py +90 -0
- lcc/benchmarking/report.py +91 -0
- lcc/benchmarking/runner.py +316 -0
- lcc/benchmarking/schemas.py +125 -0
- lcc/cleaning/__init__.py +40 -0
- lcc/cleaning/boilerplate.py +75 -0
- lcc/cleaning/deduplicate.py +88 -0
- lcc/cleaning/normalize.py +184 -0
- lcc/cleaning/speech.py +313 -0
- lcc/cli.py +1614 -0
- lcc/compressor.py +119 -0
- lcc/inspection/__init__.py +56 -0
- lcc/inspection/inspector.py +678 -0
- lcc/inspection/report.py +100 -0
- lcc/inspection/schemas.py +186 -0
- lcc/intake/__init__.py +17 -0
- lcc/intake/parser.py +182 -0
- lcc/intake/pipeline.py +170 -0
- lcc/lexical_selection.py +320 -0
- lcc/mcp_server.py +357 -0
- lcc/pipeline.py +147 -0
- lcc/prompt_builder/__init__.py +7 -0
- lcc/prompt_builder/builder.py +41 -0
- lcc/prompt_builder/templates.py +223 -0
- lcc/py.typed +1 -0
- lcc/relevance/__init__.py +164 -0
- lcc/relevance/blocks.py +201 -0
- lcc/relevance/compactor.py +2257 -0
- lcc/relevance/decisions.py +266 -0
- lcc/relevance/graph.py +224 -0
- lcc/relevance/jev.py +347 -0
- lcc/relevance/laya.py +360 -0
- lcc/relevance/provider.py +221 -0
- lcc/relevance/safety.py +75 -0
- lcc/relevance/sufficiency.py +69 -0
- lcc/relevance/trim.py +254 -0
- lcc/relevance/verifier.py +327 -0
- lcc/reporting/__init__.py +23 -0
- lcc/reporting/explain.py +270 -0
- lcc/reporting/report.py +121 -0
- lcc/router/__init__.py +57 -0
- lcc/router/cli.py +138 -0
- lcc/router/cloud_client.py +112 -0
- lcc/router/config.py +150 -0
- lcc/router/context_adapter.py +141 -0
- lcc/router/errors.py +15 -0
- lcc/router/eval_runner.py +179 -0
- lcc/router/features.py +151 -0
- lcc/router/final_formatter.py +75 -0
- lcc/router/fireworks_client.py +17 -0
- lcc/router/lcc_adapter.py +13 -0
- lcc/router/policy.py +64 -0
- lcc/router/prompt_builder.py +48 -0
- lcc/router/router.py +199 -0
- lcc/router/schemas.py +178 -0
- lcc/router/token_accounting.py +8 -0
- lcc/schemas.py +110 -0
- lcc/semantic_retrieval/__init__.py +42 -0
- lcc/semantic_retrieval/boundary.py +500 -0
- lcc/semantic_retrieval/execution.py +481 -0
- lcc/token_budget/__init__.py +29 -0
- lcc/token_budget/counters.py +252 -0
- lcc/token_budget/pricing.py +109 -0
- lcc/toon.py +74 -0
- local_context_compiler-0.4.0.dist-info/METADATA +683 -0
- local_context_compiler-0.4.0.dist-info/RECORD +77 -0
- local_context_compiler-0.4.0.dist-info/WHEEL +5 -0
- local_context_compiler-0.4.0.dist-info/entry_points.txt +2 -0
- local_context_compiler-0.4.0.dist-info/licenses/LICENSE +21 -0
- local_context_compiler-0.4.0.dist-info/top_level.txt +1 -0
lcc/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Local Context Compiler (lcc).
|
|
2
|
+
|
|
3
|
+
A deterministic, local-first toolkit that cleans, deduplicates, structures, and measures
|
|
4
|
+
text context before it is sent to a large language model. The MVP performs no network
|
|
5
|
+
calls and requires no API key (see docs/architecture.md and the ADRs in docs/adr/).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
__version__ = version("local-context-compiler")
|
|
14
|
+
except PackageNotFoundError: # running from a source tree without an installation
|
|
15
|
+
__version__ = "0.4.0"
|
|
16
|
+
|
|
17
|
+
from lcc.agents import (
|
|
18
|
+
LocalAgent,
|
|
19
|
+
LocalAgentConfig,
|
|
20
|
+
create_local_agent_from_env,
|
|
21
|
+
)
|
|
22
|
+
from lcc.compressor import CompressionResult, LccCompressor, LccOptimizer
|
|
23
|
+
from lcc.intake import (
|
|
24
|
+
IntakePipeline,
|
|
25
|
+
IntakeResult,
|
|
26
|
+
LccIntake,
|
|
27
|
+
ParsedIntake,
|
|
28
|
+
ReadinessState,
|
|
29
|
+
StructuredBrief,
|
|
30
|
+
parse_intake,
|
|
31
|
+
process_intake,
|
|
32
|
+
)
|
|
33
|
+
from lcc.pipeline import OptimizationRequest, OptimizationResult, optimize
|
|
34
|
+
from lcc.router import (
|
|
35
|
+
FinalAnswer,
|
|
36
|
+
LCCRouter,
|
|
37
|
+
RouteDecision,
|
|
38
|
+
TaskInput,
|
|
39
|
+
VerificationDecision,
|
|
40
|
+
VerificationResult,
|
|
41
|
+
)
|
|
42
|
+
from lcc.toon import encode_toon
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"__version__",
|
|
46
|
+
"LccCompressor",
|
|
47
|
+
"LccOptimizer",
|
|
48
|
+
"CompressionResult",
|
|
49
|
+
"OptimizationRequest",
|
|
50
|
+
"OptimizationResult",
|
|
51
|
+
"optimize",
|
|
52
|
+
"encode_toon",
|
|
53
|
+
"LccIntake",
|
|
54
|
+
"IntakePipeline",
|
|
55
|
+
"IntakeResult",
|
|
56
|
+
"ParsedIntake",
|
|
57
|
+
"ReadinessState",
|
|
58
|
+
"StructuredBrief",
|
|
59
|
+
"parse_intake",
|
|
60
|
+
"process_intake",
|
|
61
|
+
"LocalAgent",
|
|
62
|
+
"LocalAgentConfig",
|
|
63
|
+
"create_local_agent_from_env",
|
|
64
|
+
"LCCRouter",
|
|
65
|
+
"TaskInput",
|
|
66
|
+
"FinalAnswer",
|
|
67
|
+
"RouteDecision",
|
|
68
|
+
"VerificationDecision",
|
|
69
|
+
"VerificationResult",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
lcc/agents/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Local LLM agents, solvers, and quality verification gates."""
|
|
2
|
+
|
|
3
|
+
from lcc.agents.local_agent import (
|
|
4
|
+
ChatFormatter,
|
|
5
|
+
LocalAgent,
|
|
6
|
+
LocalAgentConfig,
|
|
7
|
+
create_local_agent_from_env,
|
|
8
|
+
detect_model_family,
|
|
9
|
+
)
|
|
10
|
+
from lcc.agents.local_solver import (
|
|
11
|
+
HTTPLocalSolver,
|
|
12
|
+
LocalAgentSolver,
|
|
13
|
+
LocalSolver,
|
|
14
|
+
MockLocalSolver,
|
|
15
|
+
create_local_solver_from_env,
|
|
16
|
+
)
|
|
17
|
+
from lcc.agents.local_verifier import (
|
|
18
|
+
LocalLLMVerifier,
|
|
19
|
+
RuleBasedVerifier,
|
|
20
|
+
create_verifier,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"LocalAgent",
|
|
25
|
+
"LocalAgentConfig",
|
|
26
|
+
"create_local_agent_from_env",
|
|
27
|
+
"detect_model_family",
|
|
28
|
+
"ChatFormatter",
|
|
29
|
+
"LocalSolver",
|
|
30
|
+
"LocalAgentSolver",
|
|
31
|
+
"MockLocalSolver",
|
|
32
|
+
"HTTPLocalSolver",
|
|
33
|
+
"create_local_solver_from_env",
|
|
34
|
+
"RuleBasedVerifier",
|
|
35
|
+
"LocalLLMVerifier",
|
|
36
|
+
"create_verifier",
|
|
37
|
+
]
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Local LLM Agent specialized for Gemma 4 e4b and Qwen3.5-4B.
|
|
2
|
+
|
|
3
|
+
Provides zero-remote-token local inference, native chat templating, structured verification,
|
|
4
|
+
and health diagnostic capabilities across Ollama, llama.cpp, vLLM, MLX, and mock backends.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from lcc.router.schemas import (
|
|
19
|
+
AgentHealth,
|
|
20
|
+
LocalAnswer,
|
|
21
|
+
ModelFamily,
|
|
22
|
+
TaskFeatures,
|
|
23
|
+
TaskInput,
|
|
24
|
+
VerificationDecision,
|
|
25
|
+
VerificationResult,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def detect_model_family(name: str, explicit_family: str | None = None) -> ModelFamily:
|
|
30
|
+
"""Detect whether a model belongs to Gemma, Qwen, or generic family."""
|
|
31
|
+
if explicit_family:
|
|
32
|
+
lowered = explicit_family.lower()
|
|
33
|
+
if "gemma" in lowered:
|
|
34
|
+
return ModelFamily.GEMMA
|
|
35
|
+
if "qwen" in lowered:
|
|
36
|
+
return ModelFamily.QWEN
|
|
37
|
+
if "generic" in lowered:
|
|
38
|
+
return ModelFamily.GENERIC
|
|
39
|
+
|
|
40
|
+
name_lower = name.lower()
|
|
41
|
+
if "gemma" in name_lower:
|
|
42
|
+
return ModelFamily.GEMMA
|
|
43
|
+
if "qwen" in name_lower:
|
|
44
|
+
return ModelFamily.QWEN
|
|
45
|
+
return ModelFamily.GENERIC
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ChatFormatter:
|
|
49
|
+
"""Formats prompts according to model-specific chat templates."""
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def format(
|
|
53
|
+
family: ModelFamily,
|
|
54
|
+
user_message: str,
|
|
55
|
+
system_message: str | None = None,
|
|
56
|
+
) -> tuple[str, list[str]]:
|
|
57
|
+
"""Return (formatted_prompt, stop_tokens)."""
|
|
58
|
+
if family == ModelFamily.GEMMA:
|
|
59
|
+
stop_tokens = ["<end_of_turn>", "<eos>", "<start_of_turn>"]
|
|
60
|
+
if system_message:
|
|
61
|
+
content = f"[System Instructions]\n{system_message}\n\n[Task]\n{user_message}"
|
|
62
|
+
else:
|
|
63
|
+
content = user_message
|
|
64
|
+
prompt = f"<start_of_turn>user\n{content}<end_of_turn>\n<start_of_turn>model\n"
|
|
65
|
+
return prompt, stop_tokens
|
|
66
|
+
|
|
67
|
+
if family == ModelFamily.QWEN:
|
|
68
|
+
stop_tokens = ["<|im_end|>", "<|endoftext|>"]
|
|
69
|
+
sys_part = (
|
|
70
|
+
f"<|im_start|>system\n{system_message}<|im_end|>\n"
|
|
71
|
+
if system_message
|
|
72
|
+
else "<|im_start|>system\nYou are a helpful and precise assistant.<|im_end|>\n"
|
|
73
|
+
)
|
|
74
|
+
prompt = (
|
|
75
|
+
f"{sys_part}<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant\n"
|
|
76
|
+
)
|
|
77
|
+
return prompt, stop_tokens
|
|
78
|
+
|
|
79
|
+
# Generic / default
|
|
80
|
+
stop_tokens = ["</s>", "<|endoftext|>"]
|
|
81
|
+
if system_message:
|
|
82
|
+
prompt = f"System: {system_message}\n\nUser: {user_message}\n\nAssistant:\n"
|
|
83
|
+
else:
|
|
84
|
+
prompt = f"User: {user_message}\n\nAssistant:\n"
|
|
85
|
+
return prompt, stop_tokens
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class LocalAgentConfig:
|
|
90
|
+
backend: str = "mock"
|
|
91
|
+
model_name: str = "gemma-4-e4b"
|
|
92
|
+
endpoint: str = "http://127.0.0.1:11434"
|
|
93
|
+
family: ModelFamily | str = "auto"
|
|
94
|
+
temperature: float = 0.0
|
|
95
|
+
max_tokens: int = 2048
|
|
96
|
+
timeout_seconds: float = 30.0
|
|
97
|
+
quantization: str = "e4b"
|
|
98
|
+
|
|
99
|
+
def resolved_family(self) -> ModelFamily:
|
|
100
|
+
if isinstance(self.family, ModelFamily):
|
|
101
|
+
return self.family
|
|
102
|
+
if self.family != "auto":
|
|
103
|
+
return detect_model_family("", self.family)
|
|
104
|
+
return detect_model_family(self.model_name)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class LocalAgent:
|
|
108
|
+
"""Unified Local LLM Agent for high-performance zero-token task solving."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, config: LocalAgentConfig | None = None) -> None:
|
|
111
|
+
self.config = config or LocalAgentConfig()
|
|
112
|
+
self.family = self.config.resolved_family()
|
|
113
|
+
self.backend = self.config.backend.lower()
|
|
114
|
+
self.model_name = self.config.model_name
|
|
115
|
+
self.endpoint = self.config.endpoint.rstrip("/")
|
|
116
|
+
|
|
117
|
+
def solve(self, task: TaskInput, prompt: str | None = None) -> LocalAnswer:
|
|
118
|
+
"""Execute local solver inference on a task with 0 remote tokens."""
|
|
119
|
+
from lcc.router.prompt_builder import build_local_prompt
|
|
120
|
+
|
|
121
|
+
effective_prompt = prompt or build_local_prompt(task, task.context)
|
|
122
|
+
started = time.perf_counter()
|
|
123
|
+
|
|
124
|
+
if self.backend == "mock":
|
|
125
|
+
return self._solve_mock(task, effective_prompt, started)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
raw_text = self._call_backend(effective_prompt)
|
|
129
|
+
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
130
|
+
return LocalAnswer(
|
|
131
|
+
answer=raw_text.strip(),
|
|
132
|
+
model_name=self.model_name,
|
|
133
|
+
latency_ms=latency_ms,
|
|
134
|
+
metadata={
|
|
135
|
+
"backend": self.backend,
|
|
136
|
+
"family": self.family.value,
|
|
137
|
+
"endpoint": self.endpoint,
|
|
138
|
+
"quantization": self.config.quantization,
|
|
139
|
+
},
|
|
140
|
+
)
|
|
141
|
+
except Exception as exc:
|
|
142
|
+
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
143
|
+
return LocalAnswer(
|
|
144
|
+
answer=f"[Local Error: {exc}]",
|
|
145
|
+
model_name=self.model_name,
|
|
146
|
+
latency_ms=latency_ms,
|
|
147
|
+
metadata={
|
|
148
|
+
"backend": self.backend,
|
|
149
|
+
"error": str(exc),
|
|
150
|
+
"fallback_to_mock": True,
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def verify(
|
|
155
|
+
self,
|
|
156
|
+
task: TaskInput,
|
|
157
|
+
candidate: LocalAnswer | str,
|
|
158
|
+
features: TaskFeatures | None = None,
|
|
159
|
+
) -> VerificationResult:
|
|
160
|
+
"""Run local verification gate against a candidate answer."""
|
|
161
|
+
from lcc.router.prompt_builder import build_verifier_prompt
|
|
162
|
+
|
|
163
|
+
candidate_ans = candidate if isinstance(candidate, LocalAnswer) else LocalAnswer(
|
|
164
|
+
answer=str(candidate),
|
|
165
|
+
model_name=self.model_name,
|
|
166
|
+
latency_ms=0,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
verifier_prompt = build_verifier_prompt(task, candidate_ans)
|
|
170
|
+
|
|
171
|
+
system_instruction = (
|
|
172
|
+
"You are a strict technical answer quality verifier. "
|
|
173
|
+
"Output ONLY valid JSON matching the verifier_contract schema."
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if self.backend == "mock":
|
|
177
|
+
return self._verify_mock(task, candidate_ans)
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
raw = self._call_backend(verifier_prompt, system_message=system_instruction)
|
|
181
|
+
payload = _extract_json(raw)
|
|
182
|
+
return VerificationResult(
|
|
183
|
+
decision=VerificationDecision(str(payload["decision"])),
|
|
184
|
+
confidence=float(payload.get("confidence", 0.85)),
|
|
185
|
+
format_valid=bool(payload.get("format_valid", True)),
|
|
186
|
+
missing_requirements=[
|
|
187
|
+
str(item) for item in payload.get("missing_requirements", [])
|
|
188
|
+
],
|
|
189
|
+
risk_reasons=[str(item) for item in payload.get("risk_reasons", [])],
|
|
190
|
+
explanation=str(payload.get("explanation", "Verified by local LLM")),
|
|
191
|
+
)
|
|
192
|
+
except Exception as exc:
|
|
193
|
+
return VerificationResult(
|
|
194
|
+
decision=(
|
|
195
|
+
VerificationDecision.ACCEPT_LOCAL
|
|
196
|
+
if candidate_ans.answer.strip()
|
|
197
|
+
else VerificationDecision.ESCALATE_REMOTE
|
|
198
|
+
),
|
|
199
|
+
confidence=0.75 if candidate_ans.answer.strip() else 0.0,
|
|
200
|
+
format_valid=bool(candidate_ans.answer.strip()),
|
|
201
|
+
missing_requirements=[] if candidate_ans.answer.strip() else ["non-empty answer"],
|
|
202
|
+
risk_reasons=[f"verifier_fallback_on_error: {exc}"] if str(exc) else [],
|
|
203
|
+
explanation=f"Fallback rule verification due to: {exc}",
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def health_check(self) -> AgentHealth:
|
|
207
|
+
"""Probe local backend availability and latency."""
|
|
208
|
+
started = time.perf_counter()
|
|
209
|
+
if self.backend == "mock":
|
|
210
|
+
return AgentHealth(
|
|
211
|
+
healthy=True,
|
|
212
|
+
status="ready (mock)",
|
|
213
|
+
model_name=self.model_name,
|
|
214
|
+
backend="mock",
|
|
215
|
+
family=self.family,
|
|
216
|
+
latency_ms=0,
|
|
217
|
+
details={"mode": "deterministic mock", "quantization": self.config.quantization},
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
test_url = (
|
|
221
|
+
f"{self.endpoint}/api/version"
|
|
222
|
+
if self.backend == "ollama"
|
|
223
|
+
else f"{self.endpoint}/v1/models"
|
|
224
|
+
)
|
|
225
|
+
try:
|
|
226
|
+
req = urllib.request.Request(test_url, headers={"User-Agent": "lcc-local-agent/1.0"})
|
|
227
|
+
with urllib.request.urlopen(req, timeout=3.0) as resp: # noqa: S310
|
|
228
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
229
|
+
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
230
|
+
return AgentHealth(
|
|
231
|
+
healthy=True,
|
|
232
|
+
status="ready",
|
|
233
|
+
model_name=self.model_name,
|
|
234
|
+
backend=self.backend,
|
|
235
|
+
family=self.family,
|
|
236
|
+
latency_ms=latency_ms,
|
|
237
|
+
details={"endpoint": self.endpoint, "response": data},
|
|
238
|
+
)
|
|
239
|
+
except Exception as exc:
|
|
240
|
+
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
241
|
+
return AgentHealth(
|
|
242
|
+
healthy=False,
|
|
243
|
+
status="offline",
|
|
244
|
+
model_name=self.model_name,
|
|
245
|
+
backend=self.backend,
|
|
246
|
+
family=self.family,
|
|
247
|
+
latency_ms=latency_ms,
|
|
248
|
+
details={"endpoint": self.endpoint, "error": str(exc)},
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
def _call_backend(self, prompt: str, system_message: str | None = None) -> str:
|
|
252
|
+
formatted_prompt, stop_tokens = ChatFormatter.format(self.family, prompt, system_message)
|
|
253
|
+
|
|
254
|
+
if self.backend == "ollama":
|
|
255
|
+
url = f"{self.endpoint}/api/generate"
|
|
256
|
+
payload = {
|
|
257
|
+
"model": self.model_name,
|
|
258
|
+
"prompt": formatted_prompt,
|
|
259
|
+
"stream": False,
|
|
260
|
+
"options": {
|
|
261
|
+
"temperature": self.config.temperature,
|
|
262
|
+
"num_predict": self.config.max_tokens,
|
|
263
|
+
"stop": stop_tokens,
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
|
+
response_data = self._http_post(url, payload)
|
|
267
|
+
return str(response_data.get("response", ""))
|
|
268
|
+
|
|
269
|
+
url = f"{self.endpoint}/v1/chat/completions"
|
|
270
|
+
if not self._endpoint_has_v1():
|
|
271
|
+
url = f"{self.endpoint}/chat/completions"
|
|
272
|
+
|
|
273
|
+
messages: list[dict[str, str]] = []
|
|
274
|
+
if system_message:
|
|
275
|
+
messages.append({"role": "system", "content": system_message})
|
|
276
|
+
messages.append({"role": "user", "content": prompt})
|
|
277
|
+
|
|
278
|
+
payload = {
|
|
279
|
+
"model": self.model_name,
|
|
280
|
+
"messages": messages,
|
|
281
|
+
"temperature": self.config.temperature,
|
|
282
|
+
"max_tokens": self.config.max_tokens,
|
|
283
|
+
"stop": stop_tokens,
|
|
284
|
+
}
|
|
285
|
+
response_data = self._http_post(url, payload)
|
|
286
|
+
choices = response_data.get("choices", [{}])
|
|
287
|
+
if choices and "message" in choices[0]:
|
|
288
|
+
return str(choices[0]["message"].get("content", ""))
|
|
289
|
+
return str(response_data)
|
|
290
|
+
|
|
291
|
+
def _endpoint_has_v1(self) -> bool:
|
|
292
|
+
return "/v1" in self.endpoint
|
|
293
|
+
|
|
294
|
+
def _http_post(self, url: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
295
|
+
data_bytes = json.dumps(payload).encode("utf-8")
|
|
296
|
+
req = urllib.request.Request(
|
|
297
|
+
url,
|
|
298
|
+
data=data_bytes,
|
|
299
|
+
headers={"Content-Type": "application/json"},
|
|
300
|
+
method="POST",
|
|
301
|
+
)
|
|
302
|
+
with urllib.request.urlopen(req, timeout=self.config.timeout_seconds) as response: # noqa: S310
|
|
303
|
+
return json.loads(response.read().decode("utf-8"))
|
|
304
|
+
|
|
305
|
+
def _solve_mock(self, task: TaskInput, prompt: str, started: float) -> LocalAnswer:
|
|
306
|
+
context = task.context.strip()
|
|
307
|
+
expected = (task.expected_format or "").lower()
|
|
308
|
+
if "json" in expected:
|
|
309
|
+
answer = json.dumps(
|
|
310
|
+
{"answer": _first_sentence(context) or f"Answer for {task.task_id}"}
|
|
311
|
+
)
|
|
312
|
+
elif "markdown table" in expected or "table" in expected:
|
|
313
|
+
ans_val = _first_sentence(context) or f"Answer for {task.task_id}"
|
|
314
|
+
answer = f"| Item | Value |\n| --- | --- |\n| Result | {ans_val} |"
|
|
315
|
+
else:
|
|
316
|
+
answer = _first_sentence(context) or f"Mock local answer for {task.task_id}."
|
|
317
|
+
|
|
318
|
+
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
319
|
+
return LocalAnswer(
|
|
320
|
+
answer=answer,
|
|
321
|
+
model_name=self.model_name,
|
|
322
|
+
latency_ms=latency_ms,
|
|
323
|
+
metadata={
|
|
324
|
+
"backend": "mock",
|
|
325
|
+
"family": self.family.value,
|
|
326
|
+
"quantization": self.config.quantization,
|
|
327
|
+
"prompt_len": len(prompt),
|
|
328
|
+
},
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def _verify_mock(self, task: TaskInput, candidate: LocalAnswer) -> VerificationResult:
|
|
332
|
+
answer = candidate.answer.strip()
|
|
333
|
+
format_valid = True
|
|
334
|
+
missing: list[str] = []
|
|
335
|
+
if not answer:
|
|
336
|
+
format_valid = False
|
|
337
|
+
missing.append("non-empty answer")
|
|
338
|
+
|
|
339
|
+
if task.expected_format and "json" in task.expected_format.lower():
|
|
340
|
+
try:
|
|
341
|
+
json.loads(answer)
|
|
342
|
+
except Exception:
|
|
343
|
+
format_valid = False
|
|
344
|
+
missing.append("valid JSON")
|
|
345
|
+
|
|
346
|
+
decision = (
|
|
347
|
+
VerificationDecision.ACCEPT_LOCAL
|
|
348
|
+
if format_valid
|
|
349
|
+
else VerificationDecision.ESCALATE_REMOTE
|
|
350
|
+
)
|
|
351
|
+
confidence = 0.90 if format_valid else 0.20
|
|
352
|
+
return VerificationResult(
|
|
353
|
+
decision=decision,
|
|
354
|
+
confidence=confidence,
|
|
355
|
+
format_valid=format_valid,
|
|
356
|
+
missing_requirements=missing,
|
|
357
|
+
risk_reasons=[] if format_valid else ["format_invalid"],
|
|
358
|
+
explanation="Mock verification gate evaluation",
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _first_sentence(text: str) -> str:
|
|
363
|
+
for separator in [". ", "\n"]:
|
|
364
|
+
if separator in text:
|
|
365
|
+
return text.split(separator, 1)[0].strip().rstrip(".") + "."
|
|
366
|
+
return text[:240].strip()
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _extract_json(text: str) -> dict[str, Any]:
|
|
370
|
+
cleaned = text.strip()
|
|
371
|
+
if cleaned.startswith("```"):
|
|
372
|
+
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned, flags=re.IGNORECASE)
|
|
373
|
+
cleaned = re.sub(r"\s*```$", "", cleaned)
|
|
374
|
+
try:
|
|
375
|
+
val = json.loads(cleaned)
|
|
376
|
+
if isinstance(val, dict):
|
|
377
|
+
return val
|
|
378
|
+
except json.JSONDecodeError:
|
|
379
|
+
pass
|
|
380
|
+
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
|
|
381
|
+
if match:
|
|
382
|
+
val = json.loads(match.group(0))
|
|
383
|
+
if isinstance(val, dict):
|
|
384
|
+
return val
|
|
385
|
+
raise ValueError(f"Could not parse valid JSON from: {text[:200]}")
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def create_local_agent_from_env() -> LocalAgent:
|
|
389
|
+
"""Create configured LocalAgent from environment variables or configs/models.yaml."""
|
|
390
|
+
backend = os.getenv("LOCAL_MODEL_BACKEND", "mock")
|
|
391
|
+
model_name = os.getenv("LOCAL_MODEL_NAME", "gemma-4-e4b")
|
|
392
|
+
endpoint = os.getenv("LOCAL_MODEL_ENDPOINT", "http://127.0.0.1:11434")
|
|
393
|
+
family = os.getenv("LOCAL_MODEL_FAMILY", "auto")
|
|
394
|
+
quantization = os.getenv("LOCAL_MODEL_QUANTIZATION", "e4b")
|
|
395
|
+
|
|
396
|
+
config = LocalAgentConfig(
|
|
397
|
+
backend=backend,
|
|
398
|
+
model_name=model_name,
|
|
399
|
+
endpoint=endpoint,
|
|
400
|
+
family=family,
|
|
401
|
+
quantization=quantization,
|
|
402
|
+
)
|
|
403
|
+
return LocalAgent(config)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Local solver interfaces and adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
|
|
8
|
+
from lcc.agents.local_agent import (
|
|
9
|
+
LocalAgent,
|
|
10
|
+
LocalAgentConfig,
|
|
11
|
+
create_local_agent_from_env,
|
|
12
|
+
)
|
|
13
|
+
from lcc.router.schemas import LocalAnswer, TaskInput
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LocalSolver(ABC):
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def solve(self, task: TaskInput, prompt: str) -> LocalAnswer:
|
|
19
|
+
"""Return a local answer with zero remote tokens used."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class LocalAgentSolver(LocalSolver):
|
|
23
|
+
"""Bridge adapter that routes requests through the specialized LocalAgent."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, agent: LocalAgent | None = None) -> None:
|
|
26
|
+
self.agent = agent or create_local_agent_from_env()
|
|
27
|
+
|
|
28
|
+
def solve(self, task: TaskInput, prompt: str) -> LocalAnswer:
|
|
29
|
+
return self.agent.solve(task, prompt)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MockLocalSolver(LocalSolver):
|
|
33
|
+
"""Deterministic local solver for tests and unconfigured environments."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, model_name: str = "mock-local") -> None:
|
|
36
|
+
self.model_name = model_name
|
|
37
|
+
self._agent = LocalAgent(LocalAgentConfig(backend="mock", model_name=model_name))
|
|
38
|
+
|
|
39
|
+
def solve(self, task: TaskInput, prompt: str) -> LocalAnswer:
|
|
40
|
+
return self._agent.solve(task, prompt)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class HTTPLocalSolver(LocalSolver):
|
|
44
|
+
"""Adapter for Ollama, llama.cpp, and OpenAI-compatible endpoints."""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
backend: str,
|
|
49
|
+
model_name: str,
|
|
50
|
+
endpoint: str,
|
|
51
|
+
family: str = "auto",
|
|
52
|
+
quantization: str = "e4b",
|
|
53
|
+
) -> None:
|
|
54
|
+
self.backend = backend
|
|
55
|
+
self.model_name = model_name
|
|
56
|
+
self.endpoint = endpoint.rstrip("/")
|
|
57
|
+
self._agent = LocalAgent(
|
|
58
|
+
LocalAgentConfig(
|
|
59
|
+
backend=backend,
|
|
60
|
+
model_name=model_name,
|
|
61
|
+
endpoint=endpoint,
|
|
62
|
+
family=family,
|
|
63
|
+
quantization=quantization,
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
def solve(self, task: TaskInput, prompt: str) -> LocalAnswer:
|
|
68
|
+
return self._agent.solve(task, prompt)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def create_local_solver_from_env() -> LocalSolver:
|
|
72
|
+
backend = os.getenv("LOCAL_MODEL_BACKEND", "mock").lower()
|
|
73
|
+
model = os.getenv("LOCAL_MODEL_NAME", "gemma-4-e4b")
|
|
74
|
+
if backend == "mock":
|
|
75
|
+
return MockLocalSolver(model)
|
|
76
|
+
endpoint = os.getenv("LOCAL_MODEL_ENDPOINT")
|
|
77
|
+
if not endpoint:
|
|
78
|
+
return MockLocalSolver(f"{model} (mock: missing LOCAL_MODEL_ENDPOINT)")
|
|
79
|
+
if backend not in {"ollama", "llamacpp", "vllm", "transformers", "mlx", "openai_compat"}:
|
|
80
|
+
return MockLocalSolver(f"{model} (mock: unsupported backend {backend})")
|
|
81
|
+
family = os.getenv("LOCAL_MODEL_FAMILY", "auto")
|
|
82
|
+
quantization = os.getenv("LOCAL_MODEL_QUANTIZATION", "e4b")
|
|
83
|
+
return HTTPLocalSolver(
|
|
84
|
+
backend=backend,
|
|
85
|
+
model_name=model,
|
|
86
|
+
endpoint=endpoint,
|
|
87
|
+
family=family,
|
|
88
|
+
quantization=quantization,
|
|
89
|
+
)
|