Datasets:
File size: 8,257 Bytes
4a372d3 | 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 125 126 127 128 129 130 131 132 133 134 | """One Harbor action loop for every requirements-only scenario in the pool."""
import hashlib
import json
from datetime import datetime, timezone
from harbor.agents.base import BaseAgent
from harbor.agents.agent_auth_resolution import ModelConnectionSpec
from harbor.agents.capabilities import AgentCapabilities
from harbor.agents.options import AgentOptions
from pydantic import Field
from typing import Literal
from . import presentation, participant
from harbor.models.model_api_format import ModelApiFormat
from harbor.models.trajectories.trajectory import Trajectory
from .model import MODEL, ACTIONS, SYSTEM, settings, OpenAIActionClient, parse_action, save, action_call_cap
def public_observation(value):
# Hashes bind evidence; they are not part of the game requirements seen by the model.
return {k:v for k,v in value.items() if k != 'binding'}
class ScenarioOptions(AgentOptions):
presentation: Literal["task-participant-v4","task-participant-v3","task-participant-v2","task-participant-v1","auto","base","task-v1","warehouse-interface-v1","warehouse-brief-v1","warehouse-combined-v1"] = "task-participant-v4"
temperature: float = Field(default=0, ge=0, le=2, allow_inf_nan=False)
class ScenarioAgent(BaseAgent):
capabilities = AgentCapabilities(atif=True)
options_model = ScenarioOptions
MODEL_CONNECTION = ModelConnectionSpec(default_provider='openai',
supported_api_formats=[ModelApiFormat.OPENAI_CHAT_COMPLETIONS],
default_api_format_by_provider={'openai':ModelApiFormat.OPENAI_CHAT_COMPLETIONS})
@staticmethod
def name(): return 'agentgridworld-actions'
def version(self): return '0.1.0'
async def setup(self, environment):
check=await environment.exec('test "$(id -u)" -ne 0 && test ! -r /var/lib/gridworld/episode.json && test ! -w /opt/gridworld/runtime/gridworld.py && test ! -r /opt/gridworld/task-config.json && test -z "$OPENAI_API_KEY"',user='agent',timeout_sec=10)
if check.return_code != 0:
raise RuntimeError('Agent permission boundary failed')
self.logs_dir.mkdir(parents=True,exist_ok=True)
from .deployment import record_environment
await record_environment(environment, self.logs_dir)
save(self.logs_dir/'permissions.json',{'nonroot_private_evidence_and_immutable_runtime':True})
async def run(self, instruction, environment, context):
model = self._parsed_model_name
connection=self.model_connection
if connection.provider != 'openai' or not connection.api_key:
raise ValueError('Configured OpenAI credential is required')
async def execute(action):
if action not in ACTIONS + ['look']:
raise ValueError('Unsupported action')
result=await environment.exec('gridworld '+action,user='agent',timeout_sec=10)
if result.return_code != 0:
raise RuntimeError('Gridworld action failed: '+(result.stderr or result.stdout or '')[:300])
return json.loads(result.stdout)
observation=await execute('look')
profile=presentation.resolve(self.options.presentation,observation)
action_only = profile == participant.ACTION_REVISION
config = settings(model, self.options.temperature, action_only=action_only)
presented=presentation.record(profile,instruction,observation)
if presented:save(self.logs_dir/'presentation.json',presented)
system=presentation.system(profile,SYSTEM)
messages=[{'role':'system','content':system},
{'role':'user','content':presentation.instruction(profile,instruction)+'\nInitial observation:\n'+presentation.observation(profile,observation)}]
steps=[{'step_id':1,'source':'system','message':system},
{'step_id':2,'source':'user','message':messages[1]['content']}]
cap = action_call_cap(observation['steps_remaining'])
identity = observation['binding']
if identity['prompt_sha256'] != hashlib.sha256(instruction.encode()).hexdigest():
raise ValueError('Instruction differs from runtime scenario contract')
endpoint = connection.candidate_base_url or 'https://api.openai.com/v1'
save(self.logs_dir/'inference_snapshot.json', {'endpoint':endpoint, **config,
'max_calls':cap, 'sdk_retries':0, 'request_timeout_seconds':30,
'conditioning':'requirements-only-v1', **identity,
'action_transport':('bare-action-v1' if action_only else 'structured JSON; ATIF tool events represent controller execution'),
**({'presentation':presented} if presented else {})})
context.n_input_tokens=0;context.n_output_tokens=0;context.n_cache_tokens=0
status='running'
def trajectory():
value={'schema_version':'ATIF-v1.8','session_id':self.session_id,
'agent':{'name':self.name(),'version':self.version(),'model_name':model},
'steps':steps,'extra':{'state':status,'conditioning':'requirements-only-v1'}}
Trajectory.model_validate(value)
save(self.logs_dir/'trajectory.json',value)
trajectory()
try:
async with OpenAIActionClient(connection.api_key, endpoint) as client:
for index in range(cap):
request={**config,'messages':messages}
call=self.logs_dir/f'call-{index:03d}'
call.mkdir(exist_ok=False)
save(call/'request.json',request)
response=await client.generate(request)
save(call/'response.json',response.model_dump(mode='json'))
save(call/'receipt.json',{'request_id':response._request_id,'received_at':datetime.now(timezone.utc).isoformat()})
usage=response.usage
if usage:
context.n_input_tokens+=usage.prompt_tokens
context.n_output_tokens+=usage.completion_tokens
context.n_cache_tokens+=getattr(usage.prompt_tokens_details,'cached_tokens',0) or 0
body=parse_action(response, model, action_only=action_only)
messages.append({'role':'assistant','content':response.choices[0].message.content})
previous=observation
observation=await execute(body['action'])
save(call/'transition.json',{'action_index':index,'action':body['action'],'observation':observation})
if observation['binding'] != identity:
raise ValueError('Runtime scenario changed during episode')
call_id=f'action-{index}'
steps.append({'step_id':len(steps)+1,'source':'agent','model_name':model,
'message':response.choices[0].message.content,
'tool_calls':[{'tool_call_id':call_id,'function_name':'gridworld','arguments':{'action':body['action']}}],
'observation':{'results':[{'source_call_id':call_id,'content':presentation.observation(profile,observation,previous,body['action'])}]},
'extra':{'action_index':index,'response_id':response.id}})
messages.append({'role':'user','content':'Environment observation:\n'+presentation.observation(profile,observation,previous,body['action'])})
trajectory()
if observation['terminal']:
status='completed';break
else:
raise RuntimeError('Model call cap reached without a terminal episode')
except BaseException as exc:
status='failed'
# Preserve status without serializing exception details that could contain credentials.
save(self.logs_dir/'failure.json',{'type':type(exc).__name__})
raise
finally:
context.metadata={'conditioning':'requirements-only-v1','model_calls':sum(1 for _ in self.logs_dir.glob('call-*/response.json')),'state':status}
trajectory()
save(self.logs_dir/'agent-result.json',context.model_dump(mode='json'))
|