"""Load the native V9 checkpoint and apply its exported harmful-response policy.""" import json import os from pathlib import Path os.environ.setdefault('USE_TF','0') os.environ.setdefault('USE_FLAX','0') def apply_policy(probability_yes, policy): probability_yes=round(float(probability_yes),4) if not 0<=probability_yes<=1:raise ValueError('Invalid harmful-response probability') return {'response_harm':'yes' if probability_yes>=policy['threshold'] else 'no', 'probability_yes':probability_yes,'threshold':policy['threshold']} class Guard: def __init__(self,model_directory,device='cpu'): import laya self.path=Path(model_directory) self.questions=json.loads((self.path/'guard_question.json').read_text(encoding='utf-8')) self.policy=json.loads((self.path/'deployment_policy.json').read_text(encoding='utf-8')) self.agent=laya.Agent(str(self.path),device=device,fast=False,compile=False) def predict(self,prompt,response): """One response-harm decision using the run's development-frozen threshold. Keep each input intact. This public-SDK call may have a different batch shape from benchmark evaluation, so probability parity is not guaranteed. """ from laya.common import build_sequence,serialize_state if not isinstance(prompt,str) or not prompt.strip() or not isinstance(response,str) or not response.strip(): raise ValueError('Prompt and response must be nonempty strings') state={'user_prompt':prompt,'assistant_response':response} question=self.questions['response_harm'] q={'t':'choice','ins':question['instructions'],'crit':question['criteria']} tok=self.agent.tok empty,_=build_sequence(tok,'',q,self.agent.cfg['max_len'],self.agent.cfg['head_max_len']) ids=tok(serialize_state(state).replace(tok.mask_token,' '),add_special_tokens=False)['input_ids'] if len(ids)>self.agent.cfg['max_len']-len(empty):raise ValueError('Input exceeds the trained context budget; no silent truncation') answer=self.agent.predict(state,{'response_harm':question})['answers']['response_harm'] result=apply_policy(answer['probabilities']['yes'],self.policy) result['sdk_choice_at_default_threshold']=answer['choice'] return result