Datasets:
Download runner/agentgridworld/model.py from bytkim/AgentGridWorld-Hard: direct link, hf CLI and curl.
- Browser
- Download file 4.28 kB
-
https://huggingface.co/datasets/bytkim/AgentGridWorld-Hard/resolve/main/runner/agentgridworld/model.py
- Command line
-
hf download hf://datasets/bytkim/AgentGridWorld-Hard/runner/agentgridworld/model.py
-
curl -L -o model.py https://huggingface.co/datasets/bytkim/AgentGridWorld-Hard/resolve/main/runner/agentgridworld/model.py
4.28 kB
| """Small Harbor external agent: one structured model action per game transition. | |
| The model credential stays on the host. It is never injected into the sandbox. | |
| """ | |
| import json | |
| from pathlib import Path | |
| import os | |
| from datetime import datetime, timezone | |
| MODEL = 'gpt-4o-mini-2024-07-18' | |
| ACTIONS = ['up','down','left','right','stop'] | |
| FORMAT = {'type':'json_schema','json_schema':{'name':'gridworld_action','strict':True, | |
| 'schema':{'type':'object','properties':{'action':{'type':'string','enum':ACTIONS}, | |
| 'status':{'type':'string'}},'required':['action','status'],'additionalProperties':False}}} | |
| SYSTEM = ('You are controlling a gridworld through one action at a time. Follow the task requirements. ' | |
| 'Return your next action and a short user-facing status update using the required JSON format. ' | |
| 'Each environment observation is factual feedback. You have no other tools.') | |
| def save(path, value): | |
| path=Path(path); temp=path.with_suffix('.tmp') | |
| with temp.open('w') as f: | |
| json.dump(value,f,indent=2);f.write('\n');f.flush();os.fsync(f.fileno()) | |
| os.replace(temp,path) | |
| def parse_content(content, action_only=False): | |
| if action_only: | |
| if not isinstance(content, str) or content.strip() not in ACTIONS: | |
| raise ValueError('Expected one bare lowercase action') | |
| return {'action':content.strip()} | |
| body=json.loads(content) | |
| if not isinstance(body,dict) or set(body)!={'action','status'} or body['action'] not in ACTIONS or not isinstance(body['status'],str): | |
| raise ValueError('Malformed action response') | |
| return body | |
| def action_call_cap(budget): | |
| if type(budget) is not int or not 1 <= budget <= 48: | |
| raise ValueError('Unexpected initial action budget') | |
| return budget + 1 | |
| def parse_action(response, expected_model=MODEL, action_only=False): | |
| if response.model != expected_model: | |
| raise ValueError('Returned model snapshot differs from requested model') | |
| choice=response.choices[0] | |
| if choice.finish_reason != 'stop' or choice.message.refusal: | |
| raise ValueError('Model response truncated, refused, or otherwise incomplete') | |
| return parse_content(choice.message.content, action_only) | |
| SETTINGS = {'model':MODEL, 'temperature':0, 'top_p':1, 'max_tokens':256, 'seed':0, | |
| 'response_format':FORMAT, 'n':1, 'stream':False, 'store':False, | |
| 'frequency_penalty':0, 'presence_penalty':0, 'stop':None, 'logprobs':False, | |
| 'service_tier':'default'} | |
| LUNA = 'gpt-6-luna' | |
| TERRA = 'gpt-6.1-terra' | |
| PROFILES = { | |
| MODEL: SETTINGS, | |
| LUNA: {k: v for k, v in SETTINGS.items() | |
| if k not in ('model', 'max_tokens', 'seed', 'frequency_penalty', 'presence_penalty')} | |
| | {'model': LUNA, 'max_completion_tokens': 256, | |
| 'reasoning_effort': 'none', 'verbosity': 'low'}, | |
| } | |
| # Same structured-action, no-reasoning contract; no provider tool calls. | |
| PROFILES[TERRA] = {**PROFILES[LUNA], 'model':TERRA} | |
| def settings(model, temperature=0, action_only=False): | |
| """Closed, explicit provider profiles; no task-specific prompt/sampling overrides.""" | |
| import copy | |
| if model not in PROFILES: | |
| raise ValueError('Unknown model profile: ' + model) | |
| if type(temperature) not in (int,float) or not 0 <= temperature <= 2: | |
| raise ValueError('Temperature must be finite and between 0 and 2') | |
| result=copy.deepcopy(PROFILES[model]);result['temperature']=0 if temperature==0 else temperature | |
| if action_only:result.pop('response_format') | |
| return result | |
| class OpenAIActionClient: | |
| """Provider adapter; the Harbor loop only sees recorded responses and actions.""" | |
| def __init__(self, key, endpoint): | |
| from openai import AsyncOpenAI | |
| if endpoint.rstrip('/') != 'https://api.openai.com/v1': | |
| raise ValueError('This qualification pins the official OpenAI endpoint') | |
| self.client = AsyncOpenAI(api_key=key, base_url=endpoint, max_retries=0, timeout=30) | |
| async def __aenter__(self): | |
| await self.client.__aenter__() | |
| return self | |
| async def __aexit__(self, *args): | |
| return await self.client.__aexit__(*args) | |
| async def generate(self, request): | |
| return await self.client.chat.completions.create(**request) | |