File size: 4,741 Bytes
53d2a87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import httpx
from harness.adapters import Adapter, Reply
from harness.verifier import verify
PROMPTS = Path(__file__).resolve().parent / "prompts"
REFUSED = 429
@dataclass
class HarnessResult:
answer: Any
verified: bool
errors: str = ""
trace: str = ""
steps: int = 0
attempts: list[str] = field(default_factory=list)
def complete(slm_url: str, prompt: str, max_tokens: int, stop: list[str]) -> Reply:
try:
with httpx.Client(timeout=None) as http:
response = http.post(
slm_url.rstrip("/") + "/v1/completions",
json={"model": "slm", "prompt": prompt, "max_tokens": max_tokens, "stop": stop},
)
except httpx.HTTPError as exc:
return Reply("", failed=f"the model call failed ({type(exc).__name__})", cap=max_tokens)
if response.status_code == REFUSED:
return Reply("", failed="the model call limit for this item is reached", cap=max_tokens, final=True)
if response.status_code != 200:
return Reply("", failed=f"the model call failed with status {response.status_code}", cap=max_tokens)
try:
data = response.json()
except ValueError:
return Reply("", failed="the model reply was not valid JSON", cap=max_tokens)
if not isinstance(data, dict):
return Reply("", failed="the model reply was not an object", cap=max_tokens)
choices = data.get("choices")
choice = choices[0] if isinstance(choices, list) and choices and isinstance(choices[0], dict) else {}
usage = data.get("usage") if isinstance(data.get("usage"), dict) else {}
tokens = usage.get("completion_tokens")
return Reply(
text=str(choice.get("text") or "").strip(),
finish=str(choice.get("finish_reason") or ""),
tokens=tokens if isinstance(tokens, int) and tokens > 0 else 0,
cap=max_tokens,
)
def run_harness(
task: dict[str, Any],
*,
adapter: Adapter,
slm_url: str,
tools_url: str,
config: dict[str, Any],
) -> HarnessResult:
max_tokens = int((config.get("slm") or {}).get("max_new_tokens") or 256)
max_steps = int((config.get("harness") or {}).get("max_steps") or 3)
compaction = adapter.name == "context_compression"
if compaction:
max_steps = min(max_steps, 2)
limit = adapter.max_tokens(task, max_tokens)
kind = "task"
draft = ""
errors = ""
trace: list[str] = []
replies: list[Reply] = []
for step in range(1, max_steps + 1):
repairing = compaction and kind == "retry"
prompt = adapter.render(PROMPTS, kind, {} if repairing else task, draft=draft,
errors=errors[:512] if repairing else errors, limit=limit, tools_url=tools_url)
reply = complete(slm_url, prompt, limit, adapter.stop)
replies.append(reply)
if repairing and not draft.strip():
# A transport fault can leave the repair pass with no source evidence.
# Keep its reply out of the verified answer and let the system request repair.
errors = "no first-pass draft was available for a local summary"
trace.append(f"step {step}: {errors}")
return HarnessResult(answer=adapter.settle(replies[:-1], task), verified=False,
errors=errors, trace="\n".join(trace), steps=step,
attempts=[r.text for r in replies])
if reply.failed or reply.cut_short:
errors = reply.failed or "the reply was cut off before the model finished"
trace.append(f"step {step}: {errors}")
if reply.final:
break
if compaction:
draft = adapter.draft(reply.text)
kind = "retry"
else:
kind = "task"
continue
verdict = verify(adapter, reply.text, task, tools_url, reply)
trace.append(f"step {step}: {'ok' if verdict.ok else verdict.reason}")
if verdict.ok:
return HarnessResult(
answer=verdict.answer,
verified=True,
trace="\n".join(trace),
steps=step,
attempts=[r.text for r in replies],
)
errors = verdict.reason
draft = adapter.draft(reply.text)
kind = verdict.next
if not kind:
break
return HarnessResult(
answer=adapter.settle(replies, task),
verified=False,
errors=errors,
trace="\n".join(trace),
steps=len(replies),
attempts=[r.text for r in replies],
)
|