File size: 7,096 Bytes
9737348
 
 
 
 
 
 
 
 
 
 
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9737348
 
 
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9737348
f577d1f
9737348
 
 
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9737348
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9737348
f577d1f
 
 
 
 
 
 
9737348
 
f577d1f
 
9737348
f577d1f
 
9737348
f577d1f
 
 
 
 
 
 
 
 
9737348
 
 
 
 
f577d1f
9737348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f577d1f
9737348
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
9737348
f577d1f
 
 
 
9737348
 
 
 
 
f577d1f
9737348
 
f577d1f
 
 
 
 
 
 
9737348
 
f577d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Level 1 Deceit environment — factual QA, multi-turn, no adversary.

Episode structure (max_turns=3):
  - Each step where is_final=False: agent pays a -0.05 step penalty and gets
    their own reasoning appended to the next observation's context.
  - When is_final=True OR step_count >= max_turns: episode ends, full reward
    (correctness + calibration) is returned.

This multi-turn design gives GRPO meaningful trajectory length and teaches the
model to "think more when uncertain" — the core Deceit behavior.
"""

from __future__ import annotations

import json
import os
import pathlib
import random
import uuid
from typing import Optional

from openenv.core.env_server import Environment

from deceit_env.models import DeceitAction, DeceitObservation, DeceitState
from deceit_env.server.grader import Grader

_DEFAULT_DATASET = (
    pathlib.Path(__file__).parent.parent / "data" / "level1.jsonl"
)

STEP_PENALTY = -0.05
MAX_TURNS = 3


def compute_reward(
    correct: bool,
    abstain: bool,
    confidence: float,
) -> tuple[float, float]:
    """Return (correctness_reward, calibration_reward) per REWARD_DESIGN.md."""
    if abstain:
        return 0.0, 0.0

    correctness = 1.0 if correct else -1.0

    if correct:
        calibration = 0.3 if confidence > 0.7 else 0.1
    else:
        calibration = -0.3 if confidence > 0.7 else -0.1

    return correctness, calibration


class DeceitEnvironment(Environment[DeceitAction, DeceitObservation, DeceitState]):
    """OpenEnv-compliant multi-turn environment for the Deceit project.

    Level 1: factual QA with no distractors or adversary.
    Up to max_turns=3 steps per episode. Each non-final step costs a small
    step penalty and feeds the agent's reasoning back as context.
    """

    def __init__(
        self,
        dataset_path: str | pathlib.Path = _DEFAULT_DATASET,
        grader: Optional[Grader] = None,
        seed: Optional[int] = None,
    ) -> None:
        super().__init__()
        self._dataset = self._load_dataset(pathlib.Path(dataset_path))
        self._grader = grader or Grader(
            openai_api_key=os.environ.get("OPENAI_API_KEY")
        )
        self._rng = random.Random(seed)
        self._state: DeceitState = DeceitState()
        self._current_question: str = ""

    # ------------------------------------------------------------------
    # OpenEnv interface
    # ------------------------------------------------------------------

    def reset(
        self,
        seed: Optional[int] = None,
        episode_id: Optional[str] = None,
        **kwargs,
    ) -> DeceitObservation:
        """Pick a random question and initialize a new episode."""
        if seed is not None:
            self._rng = random.Random(seed)

        question_row = self._rng.choice(self._dataset)
        self._current_question = question_row["question"]
        self._state = DeceitState(
            episode_id=episode_id or str(uuid.uuid4()),
            step_count=0,
            level=1,
            ground_truth=question_row["ground_truth"],
            current_question_id=question_row["id"],
            episode_rewards=[],
            prior_reasoning=[],
            max_turns=MAX_TURNS,
        )
        return DeceitObservation(
            question=self._current_question,
            context=[],
            turn_index=0,
            max_turns=MAX_TURNS,
            level=1,
        )

    def step(
        self,
        action: DeceitAction,
        timeout_s: Optional[float] = None,
        **kwargs,
    ) -> DeceitObservation:
        """Process one agent turn.

        Non-final step: pay step penalty, append reasoning to context, continue.
        Final step (is_final=True or turn limit reached): compute full reward.
        """
        self._state.step_count += 1
        forced_final = self._state.step_count >= self._state.max_turns
        is_terminal = action.is_final or forced_final

        if not is_terminal:
            # Thinking turn: no grading, just step penalty
            self._state.prior_reasoning.append(action.reasoning)
            self._state.episode_rewards.append(STEP_PENALTY)
            context = [
                f"Your previous reasoning (turn {i + 1}): {r}"
                for i, r in enumerate(self._state.prior_reasoning)
            ]
            return DeceitObservation(
                question=self._current_question,
                context=context,
                turn_index=self._state.step_count,
                max_turns=self._state.max_turns,
                level=self._state.level,
                done=False,
                reward=STEP_PENALTY,
                metadata={"step_penalty": STEP_PENALTY, "is_final": False},
            )

        # Terminal turn: grade and compute full reward
        if action.abstain:
            correctness_r, calibration_r = 0.0, 0.0
            grader_method = "abstain"
            correct = False
        else:
            result = self._grader.check(action.answer, self._state.ground_truth)
            correct = result.correct
            correctness_r, calibration_r = compute_reward(
                correct=correct,
                abstain=False,
                confidence=action.confidence,
            )
            grader_method = result.method

        # Add step penalties already accumulated for non-final turns
        total_reward = correctness_r + calibration_r
        self._state.episode_rewards.append(total_reward)

        return DeceitObservation(
            question=self._current_question,
            context=[
                f"Your previous reasoning (turn {i + 1}): {r}"
                for i, r in enumerate(self._state.prior_reasoning)
            ],
            turn_index=self._state.step_count,
            max_turns=self._state.max_turns,
            level=self._state.level,
            done=True,
            reward=total_reward,
            metadata={
                "correctness_reward": correctness_r,
                "calibration_reward": calibration_r,
                "grader_method": grader_method,
                "correct": correct,
                "is_final": True,
                "forced_final": forced_final,
            },
        )

    @property
    def state(self) -> DeceitState:
        """Return the current internal episode state."""
        return self._state

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _load_dataset(path: pathlib.Path) -> list[dict]:
        if not path.exists():
            raise FileNotFoundError(
                f"Dataset not found at {path}. "
                "Run scripts/generate_level1_dataset.py first."
            )
        rows = []
        with open(path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line:
                    rows.append(json.loads(line))
        if not rows:
            raise ValueError(f"Dataset at {path} is empty.")
        return rows