"""Per-task executable shop; model inputs never include evaluation labels.""" import json,hashlib,random TOOLS={'search_catalog':['query','filters'],'check_fit':['item_ids','reference_width'],'ask_clarification':['field','question'],'route_service':['intent','target'],'propose_item':['item_id']} def prompt(row): return json.dumps({'instruction':'Return one JSON object only: {"tool":"name","arguments":{...}}. Use tools in order; finish by proposing an item or routing service. Ask when inheritance is unclear. No requirement does not prohibit that value. Reference footwear width is fit, not item width.','tools':TOOLS,'task':row['input']},sort_keys=True) class Shop: def __init__(self,row): self.row=row;self.calls=[];self.items=[];self.fit=[];self.proposal=None;self.service=None;self.asked=False seed=int(hashlib.sha256(row['id'].encode()).hexdigest()[:16],16);rng=random.Random(seed) value=row['value'];other='alternative';ids=['sku-'+hashlib.sha256((row['id']+str(i)).encode()).hexdigest()[:9] for i in range(3)] self.catalog=[{'id':ids[0],row['input']['field']:value,'fits':[value]},{'id':ids[1],row['input']['field']:other,'fits':[value]},{'id':ids[2],row['input']['field']:other,'fits':[]}];rng.shuffle(self.catalog) self.reply={'required':bool(seed%2),'value':value} def step(self,action): if set(action)!={'tool','arguments'} or action['tool'] not in TOOLS:raise ValueError('invalid tool object') tool=action['tool'];a=action['arguments'] if not isinstance(a,dict) or set(a)!=set(TOOLS[tool]):raise ValueError('invalid arguments') if self.proposal or self.service:raise ValueError('episode ended') f=self.row['input']['field'] if tool=='search_catalog': if a['query']!=self.row['input']['target'] or not isinstance(a['filters'],dict) or not set(a['filters'])<={f}:raise ValueError('invalid search') if any(not isinstance(v,str) for v in a['filters'].values()):raise ValueError('invalid filter') self.items=[x['id'] for x in self.catalog if all(x.get(k)==v for k,v in a['filters'].items())];result={'items':[x for x in self.catalog if x['id'] in self.items]} elif tool=='check_fit': if not isinstance(a['item_ids'],list) or not a['item_ids'] or not set(a['item_ids'])<=set(self.items) or not isinstance(a['reference_width'],str):raise ValueError('invalid fit') self.fit=[x['id'] for x in self.catalog if x['id'] in a['item_ids'] and a['reference_width'] in x['fits']];result={'compatible_ids':self.fit} elif tool=='ask_clarification': if a['field']!=f or not isinstance(a['question'],str) or not a['question']:raise ValueError('invalid question') self.asked=True;result={'answer':self.reply} elif tool=='route_service': if a['intent'] not in ['repair','return','advice'] or a['target']!=self.row['input']['target']:raise ValueError('invalid service') self.service=a;result={'routed':a} else: if a['item_id'] not in self.items:raise ValueError('unsearched item') self.proposal=a['item_id'];result={'proposal':self.proposal} self.calls.append({'action':action,'result':result});return result def success(self): r=self.row;f=r['input']['field'];s=r['status'];names=[x['action']['tool'] for x in self.calls] if r['service_intent']:return self.service=={'intent':r['service_intent'],'target':r['input']['target']} and names==['route_service'] filters={f:r['value']} if s=='explicit' or s=='ambiguous' and self.reply['required'] else {} searches=[x for x in self.calls if x['action']['tool']=='search_catalog'] if not self.proposal or self.service or len(searches)!=1 or searches[0]['action']['arguments']['filters']!=filters:return False if names.count('ask_clarification')!=int(s=='ambiguous'):return False if s=='ambiguous' and names.index('ask_clarification')>names.index('search_catalog'):return False if names.count('check_fit')!=int(s=='compatibility_only'):return False if s=='compatibility_only' and (self.proposal not in self.fit or next(x for x in self.calls if x['action']['tool']=='check_fit')['action']['arguments']['reference_width']!=r['value']):return False return True def teacher(self): r=self.row;f=r['input']['field'];s=r['status'] def call(tool,**arguments):return self.step({'tool':tool,'arguments':arguments}) if r['service_intent']:call('route_service',intent=r['service_intent'],target=r['input']['target']);return filters={} if s=='ambiguous': reply=call('ask_clarification',field=f,question='Should the new item retain that '+f+'?')['answer'] if reply['required']:filters[f]=reply['value'] elif s=='explicit':filters[f]=r['value'] call('search_catalog',query=r['input']['target'],filters=filters) ids=self.items if s=='compatibility_only':ids=call('check_fit',item_ids=ids,reference_width=r['value'])['compatible_ids'] call('propose_item',item_id=ids[0]);assert self.success() def execute(row,generate): env=Shop(row);raw_outputs=[];messages=[{'role':'user','content':prompt(row)}];error=None;error_kind=None for _ in range(5): raw=generate(messages);raw_outputs.append(raw) try:action=json.loads(raw) except (ValueError,TypeError) as exc:error=str(exc);error_kind='parse';break try:result=env.step(action) except (ValueError,TypeError,KeyError) as exc:error=str(exc);error_kind='invalid_tool';break messages.extend([{'role':'assistant','content':raw},{'role':'user','content':json.dumps({'tool_result':result},sort_keys=True)}]) if env.proposal or env.service:break return {'id':row['id'],'success':False if error else env.success(),'error':error,'error_kind':error_kind,'raw_outputs':raw_outputs,'calls':env.calls,'steps':len(env.calls)}