File size: 9,391 Bytes
371cfc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""
Ask Answer Env Environment Implementation.

A deterministic slot-filling environment where agents must decide between
asking clarifying questions or answering early to maximize reward.
"""

import random
from typing import Optional
from uuid import uuid4

from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State

from models import AskAnswerAction, AskAnswerObservation, KnownSlots


# Constants
CITIES = ["Paris", "Rome", "Tokyo", "Goa"]
DATES = ["next_weekend", "mid_feb", "march"]
BUDGETS = ["low", "mid", "high"]
STYLES = ["relax", "adventure", "food"]  # Distractor slot
MAX_STEPS = 3  # Forces agent to guess at least 1 core slot
PROMPT = "Plan a short trip for me."

# Rewards (unchanged from v0)
STEP_PENALTY = -0.05
ASK_UNKNOWN_REWARD = 0.1
ASK_KNOWN_PENALTY = -0.2
AUTO_FAIL_PENALTY = -1.0

# Graded answer rewards (v1)
ANSWER_CITY_CORRECT = 0.4
ANSWER_DATE_CORRECT = 0.4
ANSWER_BUDGET_CORRECT = 0.4
ANSWER_STYLE_CORRECT_BONUS = 0.1  # Optional nice-to-have
ANSWER_CORE_ALL_CORRECT_BONUS = 0.2
ANSWER_CORE_ANY_WRONG_PENALTY = -0.6


class AskAnswerEnvironment(Environment):
    """
    A slot-filling environment for training RL agents.

    The agent must decide between:
    - Asking clarifying questions (ASK) to reveal hidden slot values
    - Answering early (ANSWER) to end the episode

    Hidden state (city, date, budget, style) is sampled at reset with a seeded RNG.
    The agent can ask about slots to reveal their values before answering.
    
    With MAX_STEPS=3, the agent can only ask 2 slots before being forced to answer,
    creating a non-trivial ask-vs-act tradeoff. The "style" slot is a distractor
    that provides less reward than core slots (city, date, budget).

    Rewards:
    - Step penalty: -0.05 per step
    - ASK unknown slot: +0.1
    - ASK known slot: -0.2
    - ANSWER: graded per-slot (+0.4 each core, +0.1 style)
    - Core all correct bonus: +0.2
    - Core any wrong penalty: -0.6
    - Auto-fail (steps exhausted): -1.0
    """

    SUPPORTS_CONCURRENT_SESSIONS: bool = True

    def __init__(self):
        """Initialize the ask_answer_env environment."""
        self._state = State(episode_id=str(uuid4()), step_count=0)
        self._rng: random.Random = random.Random()
        
        # Hidden truth (sampled at reset)
        self._hidden_city: str = ""
        self._hidden_date: str = ""
        self._hidden_budget: str = ""
        self._hidden_style: str = ""
        
        # Known slots (revealed through ASK actions)
        self._known: KnownSlots = KnownSlots()
        self._steps_left: int = MAX_STEPS
        self._done: bool = False

    def reset(self, seed: Optional[int] = None) -> AskAnswerObservation:
        """
        Reset the environment with optional seed for determinism.

        Args:
            seed: Random seed for reproducibility

        Returns:
            AskAnswerObservation with initial state
        """
        self._state = State(episode_id=str(uuid4()), step_count=0)
        
        # Initialize RNG with seed
        if seed is not None:
            self._rng = random.Random(seed)
        else:
            self._rng = random.Random()
        
        # Sample hidden truth
        self._hidden_city = self._rng.choice(CITIES)
        self._hidden_date = self._rng.choice(DATES)
        self._hidden_budget = self._rng.choice(BUDGETS)
        self._hidden_style = self._rng.choice(STYLES)
        
        # Reset known slots and step counter
        self._known = KnownSlots()
        self._steps_left = MAX_STEPS
        self._done = False

        return AskAnswerObservation(
            prompt=PROMPT,
            known=self._known,
            steps_left=self._steps_left,
            done=False,
            reward=0.0,
        )

    def step(self, action: AskAnswerAction) -> AskAnswerObservation:  # type: ignore[override]
        """
        Execute a step in the environment.

        Args:
            action: AskAnswerAction with type 'ask' or 'answer'

        Returns:
            AskAnswerObservation with updated state and reward
        """
        if self._done:
            return AskAnswerObservation(
                prompt=PROMPT,
                known=self._known,
                steps_left=self._steps_left,
                done=True,
                reward=0.0,
            )

        self._state.step_count += 1
        
        # Always apply step penalty
        reward = STEP_PENALTY
        done = False

        if action.type == "ask":
            reward += self._handle_ask(action.slot)
            self._steps_left -= 1
            
            # Check for auto-fail
            if self._steps_left == 0:
                reward = AUTO_FAIL_PENALTY
                done = True
                
        elif action.type == "answer":
            reward += self._handle_answer(action)
            done = True

        self._done = done

        # Calculate core_correct_count when episode ends via ANSWER
        core_correct_count = None
        if done and action.type == "answer":
            core_correct_count = sum([
                action.city == self._hidden_city,
                action.date == self._hidden_date,
                action.budget == self._hidden_budget,
            ])

        return AskAnswerObservation(
            prompt=PROMPT,
            known=self._known,
            steps_left=self._steps_left,
            done=done,
            reward=reward,
            core_correct_count=core_correct_count,
        )

    def _handle_ask(self, slot: Optional[str]) -> float:
        """
        Handle ASK action - reveal a slot if unknown.

        Args:
            slot: The slot to ask about ('city', 'date', 'budget', or 'style')

        Returns:
            Reward for the ASK action
        """
        if slot == "city":
            if self._known.city is not None:
                return ASK_KNOWN_PENALTY
            self._known = KnownSlots(
                city=self._hidden_city,
                date=self._known.date,
                budget=self._known.budget,
                style=self._known.style,
            )
            return ASK_UNKNOWN_REWARD
            
        elif slot == "date":
            if self._known.date is not None:
                return ASK_KNOWN_PENALTY
            self._known = KnownSlots(
                city=self._known.city,
                date=self._hidden_date,
                budget=self._known.budget,
                style=self._known.style,
            )
            return ASK_UNKNOWN_REWARD
            
        elif slot == "budget":
            if self._known.budget is not None:
                return ASK_KNOWN_PENALTY
            self._known = KnownSlots(
                city=self._known.city,
                date=self._known.date,
                budget=self._hidden_budget,
                style=self._known.style,
            )
            return ASK_UNKNOWN_REWARD
            
        elif slot == "style":
            if self._known.style is not None:
                return ASK_KNOWN_PENALTY
            self._known = KnownSlots(
                city=self._known.city,
                date=self._known.date,
                budget=self._known.budget,
                style=self._hidden_style,
            )
            return ASK_UNKNOWN_REWARD
        
        # Invalid slot
        return ASK_KNOWN_PENALTY

    def _handle_answer(self, action: AskAnswerAction) -> float:
        """
        Handle ANSWER action with graded rewards.

        Reward structure:
        - Per-slot rewards: +0.4 for each correct core slot (city, date, budget)
        - Style bonus: +0.1 if style provided and correct (ignored if None)
        - Core bonus: +0.2 if all core slots correct
        - Core penalty: -0.6 if any core slot wrong

        Args:
            action: The answer action with city, date, budget, style values

        Returns:
            Reward for the ANSWER action
        """
        reward = 0.0
        
        # Check core slots
        city_correct = action.city == self._hidden_city
        date_correct = action.date == self._hidden_date
        budget_correct = action.budget == self._hidden_budget
        
        # Per-slot rewards for core slots
        if city_correct:
            reward += ANSWER_CITY_CORRECT
        if date_correct:
            reward += ANSWER_DATE_CORRECT
        if budget_correct:
            reward += ANSWER_BUDGET_CORRECT
        
        # Style bonus (only if provided and correct, ignored if None)
        if action.style is not None and action.style == self._hidden_style:
            reward += ANSWER_STYLE_CORRECT_BONUS
        
        # Core bonus/penalty
        core_all_correct = city_correct and date_correct and budget_correct
        if core_all_correct:
            reward += ANSWER_CORE_ALL_CORRECT_BONUS
        else:
            reward += ANSWER_CORE_ANY_WRONG_PENALTY
        
        return reward

    @property
    def state(self) -> State:
        """
        Get the current environment state.

        Returns:
            Current State with episode_id and step_count
        """
        return self._state