File size: 3,524 Bytes
c4e3582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run Harbor with each task's verifier mounted separately and read-only."""
from harbor.trial.trial import Trial, ServiceVolumeConfig
from harbor.cli.main import app
from harbor.agents.terminus_2.terminus_2 import Terminus2
from harbor.models.trajectories import Step
from contextvars import ContextVar
from datetime import datetime, timezone
import json
import litellm

original_mounts = Trial._verifier_env_mounts


def verified_mounts(self, env_config):
    mounts = original_mounts(self, env_config)
    mounts.append(ServiceVolumeConfig(type='bind',
                                      source=str(self.task.paths.tests_dir.resolve()),
                                      target='/tests', read_only=True))
    return mounts


Trial._verifier_env_mounts = verified_mounts

# Preserve and terminate provider refusals, rather than repeatedly asking the
# same blocked prompt until the eight-hour timeout. No prompts are rewritten,
# no fallback model is selected, and no model answer is synthesized.
last_refusal = ContextVar('last_refusal', default=None)
original_completion = litellm.acompletion
original_interaction = Terminus2._handle_llm_interaction
original_loop = Terminus2._run_agent_loop


class ProviderRefusal(Exception):
    pass


async def completion_with_refusal_record(*args, **kwargs):
    last_refusal.set(None)
    response = await original_completion(*args, **kwargs)
    choice = response['choices'][0]
    message = choice['message']
    if choice.get('finish_reason') == 'content_filter':
        last_refusal.set(dict(model=response.get('model'), id=response.get('id'),
                              finish_reason='content_filter',
                              refusal=message.get('refusal'),
                              content=message.get('content') or '',
                              observed_at=datetime.now(timezone.utc).isoformat()))
    return response


async def interaction_with_refusal_record(self, *args, **kwargs):
    result = await original_interaction(self, *args, **kwargs)
    refusal = last_refusal.get()
    if refusal:
        model = refusal['model'] or self._model_name.removeprefix('openrouter/')
        self._last_response_model_name = model
        self._trajectory_steps.append(Step(step_id=len(self._trajectory_steps) + 1,
                                          timestamp=refusal['observed_at'], source='agent',
                                          model_name=model, message=refusal['content'],
                                          extra={'provider_refusal': refusal}))
        (self.logs_dir / 'provider-refusal.json').write_text(json.dumps(refusal, indent=2) + '\n')
        raise ProviderRefusal('Provider returned content_filter; no replacement answer generated')
    return result


async def loop_with_refusal_stop(self, *args, **kwargs):
    try:
        return await original_loop(self, *args, **kwargs)
    except ProviderRefusal:
        # Normal task completion lets the unchanged separate grader score the
        # actual artifact (normally no answer, hence zero).
        return None


litellm.acompletion = completion_with_refusal_record
Terminus2._handle_llm_interaction = interaction_with_refusal_record
Terminus2._run_agent_loop = loop_with_refusal_stop

if __name__ == '__main__':
    # Hub downloads may omit executable bits; the verifier mount is read-only.
    from pathlib import Path
    for script in (Path(__file__).resolve().parent / 'tasks').rglob('*.sh'):
        script.chmod(script.stat().st_mode | 0o111)
    app()