File size: 5,145 Bytes
08a9326 | 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 | """Exploratory-only cap extension of the baseline raw Inspect adapter."""
from inspect_ai.model import ModelAPI, ModelOutput, ModelUsage, ChatCompletionChoice, ChatMessageAssistant, modelapi
from encoding_tax.common import ROOT, GateError, load_config, digest
from encoding_tax.tokenization import tokenizer
from encoding_tax.transport import RawTransport, usage_record, response_text, upstream_evidence
class E6ExploratoryAPI(ModelAPI):
def __init__(self, model_name, base_url=None, api_key=None, config=None, study_config="configs/study.json", audit_dir="artifacts/preflight/inspect-transport", **kwargs):
super().__init__(model_name, base_url, api_key, config=config)
self.study = load_config(study_config)
if model_name not in self.study["models"]:
raise GateError(f"Unknown pinned model alias: {model_name}")
self.profile = self.study["models"][model_name]
self.transport = RawTransport(self.profile, audit_dir, config.max_connections or 16)
self.tok = tokenizer(self.profile["tokenizer_repo"], self.profile["tokenizer_revision"]) if self.profile.get("tokenizer_repo") else None
from extensions.e6_exploratory_v2.design import require_extension
cfg,base,pin=require_extension()
if self.study!=base:raise GateError('Extension requires the pinned baseline profiles')
self.extension_ref={'path':'extensions/e6_exploratory_v2/freeze.json','sha256':digest(ROOT/'extensions/e6_exploratory_v2/freeze.json')}
def max_connections(self):
return 16
def connection_key(self):
# Inspect's default pools all instances of this custom provider together.
# The protocol ceiling is per reader, not shared by all five readers.
return f"{self.model_name}:{self.profile['provider']}"
def should_retry(self, ex):
# RawTransport alone owns the frozen maximum of three attempts.
return False
async def generate(self, input, tools, tool_choice, config):
if len(input) != 1 or tools or not isinstance(input[0].content, str):
raise GateError("Raw adapter requires a single already serialized prompt and no tools")
if config.max_tokens not in (48, 256, 512, 1024, 2048):
raise GateError("Unregistered output cap")
prompt = input[0].content
if self.tok and self.profile.get("context_length") and self.tok.count(prompt) + config.max_tokens > self.profile["context_length"]:
raise GateError("Prompt exceeds pinned context; clipping is forbidden")
phase = "answer" if config.max_tokens == self.study.get("answer_cap",8) else "source" if config.max_tokens == 4096 else "scratchpad"
response, audit = await self.transport.complete(prompt, config.max_tokens, config.stop_seqs or [], phase, metadata={"exploratory_e6": self.extension_ref})
if self.profile.get("review",{}).get("raw_upstream") and not upstream_evidence(response,prompt)["exact_prompt_forwarded"]:
raise GateError("Reviewed raw route changed its upstream serialization")
choice = response["choices"][0]
text = response_text(response, reasoning=self.profile.get('native_reasoning',False) and phase in ('source','scratchpad'))
metrics = usage_record(response, self.tok, text)
content=choice.get("message",choice)
if phase=="answer" and (metrics["reasoning_tokens"] is None or metrics["reasoning_tokens"]!=0 or content.get("reasoning") or content.get("reasoning_details")):
raise GateError("Answer-phase reasoning is missing, nonzero, or inconsistent with the visible response; audit retained")
if metrics["completion_tokens"] is not None and metrics["completion_tokens"]>config.max_tokens:
raise GateError("Provider exceeded the requested completion cap")
if self.tok and self.profile.get("review",{}).get("native_tokens"):
difference=metrics["prompt_tokens"]-self.tok.count(prompt) if metrics["prompt_tokens"] is not None else None
if difference!=self.profile["review"].get("native_prompt_offset"):
raise GateError("Native/provider prompt counts differ from the reviewed constant offset")
usage = None
if metrics["prompt_tokens"] is not None and metrics["completion_tokens"] is not None:
usage = ModelUsage(input_tokens=metrics["prompt_tokens"], output_tokens=metrics["completion_tokens"], total_tokens=metrics["prompt_tokens"]+metrics["completion_tokens"], reasoning_tokens=metrics["reasoning_tokens"], input_tokens_cache_read=metrics["cache_tokens"], total_cost=metrics["cost"])
stop = "max_tokens" if choice.get("finish_reason") == "length" else "stop"
return ModelOutput(model=self.model_name, choices=[ChatCompletionChoice(message=ChatMessageAssistant(content=text), stop_reason=stop)], usage=usage, metadata={**metrics, "response": response, "audit": audit, "prompt_sha256": digest(prompt), "native_prompt_tokens": self.tok.count(prompt) if self.tok else None, "requested_budget": config.max_tokens})
registered_api = modelapi(name='encoding_tax_e6x2')(E6ExploratoryAPI)
|