seatyyy commited on
Commit
a5fc2da
·
1 Parent(s): 192c450

update models

Browse files
client.py CHANGED
@@ -16,66 +16,33 @@ from .models import SkillForgeAction, SkillForgeObservation
16
 
17
 
18
  class SkillForgeEnv(
19
- EnvClient[SkillForgeAction, SkillForgeObservation]
20
  ):
21
  """
22
  Client for the Skill Forge Environment.
23
 
24
- This client maintains a persistent WebSocket connection to the environment server,
25
- enabling efficient multi-step interactions with lower latency.
26
- Each client instance has its own dedicated environment session on the server.
27
 
28
  Example:
29
- >>> # Connect to a running server
30
  >>> with SkillForgeEnv(base_url="http://localhost:8000") as client:
31
  ... result = client.reset()
32
- ... print(result.observation.echoed_message)
33
  ...
34
- ... result = client.step(SkillForgeAction(message="Hello!"))
35
- ... print(result.observation.echoed_message)
36
-
37
- Example with Docker:
38
- >>> # Automatically start container and connect
39
- >>> client = SkillForgeEnv.from_docker_image("skill_forge-env:latest")
40
- >>> try:
41
- ... result = client.reset()
42
- ... result = client.step(SkillForgeAction(message="Test"))
43
- ... finally:
44
- ... client.close()
45
  """
46
 
47
  def _step_payload(self, action: SkillForgeAction) -> Dict:
48
- """
49
- Convert SkillForgeAction to JSON payload for step message.
50
-
51
- Args:
52
- action: SkillForgeAction instance
53
-
54
- Returns:
55
- Dictionary representation suitable for JSON encoding
56
- """
57
- return {
58
- "message": action.message,
59
- }
60
 
61
  def _parse_result(self, payload: Dict) -> StepResult[SkillForgeObservation]:
62
- """
63
- Parse server response into StepResult[SkillForgeObservation].
64
-
65
- Args:
66
- payload: JSON response data from server
67
-
68
- Returns:
69
- StepResult with SkillForgeObservation
70
- """
71
  obs_data = payload.get("observation", {})
72
- observation = SkillForgeObservation(
73
- echoed_message=obs_data.get("echoed_message", ""),
74
- message_length=obs_data.get("message_length", 0),
75
- done=payload.get("done", False),
76
- reward=payload.get("reward"),
77
- metadata=obs_data.get("metadata", {}),
78
- )
79
 
80
  return StepResult(
81
  observation=observation,
@@ -84,15 +51,6 @@ class SkillForgeEnv(
84
  )
85
 
86
  def _parse_state(self, payload: Dict) -> State:
87
- """
88
- Parse server response into State object.
89
-
90
- Args:
91
- payload: JSON response from state request
92
-
93
- Returns:
94
- State object with episode_id and step_count
95
- """
96
  return State(
97
  episode_id=payload.get("episode_id"),
98
  step_count=payload.get("step_count", 0),
 
16
 
17
 
18
  class SkillForgeEnv(
19
+ EnvClient[SkillForgeAction, SkillForgeObservation, State]
20
  ):
21
  """
22
  Client for the Skill Forge Environment.
23
 
24
+ Maintains a persistent WebSocket connection to the environment server.
25
+ Each client instance has its own dedicated environment session.
 
26
 
27
  Example:
 
28
  >>> with SkillForgeEnv(base_url="http://localhost:8000") as client:
29
  ... result = client.reset()
30
+ ... print(result.observation.task_description)
31
  ...
32
+ ... action = SkillForgeAction(
33
+ ... action_type="raw_code",
34
+ ... content="df.sort_values('revenue', ascending=False)['product'].tolist()",
35
+ ... )
36
+ ... result = client.step(action)
37
+ ... print(result.observation.result_correct)
 
 
 
 
 
38
  """
39
 
40
  def _step_payload(self, action: SkillForgeAction) -> Dict:
41
+ return action.model_dump()
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  def _parse_result(self, payload: Dict) -> StepResult[SkillForgeObservation]:
 
 
 
 
 
 
 
 
 
44
  obs_data = payload.get("observation", {})
45
+ observation = SkillForgeObservation(**obs_data)
 
 
 
 
 
 
46
 
47
  return StepResult(
48
  observation=observation,
 
51
  )
52
 
53
  def _parse_state(self, payload: Dict) -> State:
 
 
 
 
 
 
 
 
 
54
  return State(
55
  episode_id=payload.get("episode_id"),
56
  step_count=payload.get("step_count", 0),
models.py CHANGED
@@ -19,7 +19,7 @@ class SkillForgeAction(Action):
19
  """Action for the Skill Forge environment"""
20
  action_type: Literal["create_skill", "use_skill", "raw_code"]
21
  content: str = Field(description="The content of the action. For create_skill, it is the template. For use_skill, it is the skill id. For raw_code, it is the code.")
22
- skill_name: Optional[str] # only for create_skill
23
  reasoning: str = ""
24
  params: Optional[dict] = None
25
 
 
19
  """Action for the Skill Forge environment"""
20
  action_type: Literal["create_skill", "use_skill", "raw_code"]
21
  content: str = Field(description="The content of the action. For create_skill, it is the template. For use_skill, it is the skill id. For raw_code, it is the code.")
22
+ skill_name: Optional[str] = None # only for create_skill
23
  reasoning: str = ""
24
  params: Optional[dict] = None
25
 
server/Dockerfile CHANGED
@@ -71,6 +71,9 @@ ENV PATH="/app/.venv/bin:$PATH"
71
  # Set PYTHONPATH so imports work correctly
72
  ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
 
 
 
 
74
  # Health check
75
  HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
  CMD curl -f http://localhost:8000/health || exit 1
 
71
  # Set PYTHONPATH so imports work correctly
72
  ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
 
74
+ # Enable the OpenEnv web interface
75
+ ENV ENABLE_WEB_INTERFACE="true"
76
+
77
  # Health check
78
  HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
79
  CMD curl -f http://localhost:8000/health || exit 1
server/__init__.py CHANGED
@@ -6,6 +6,9 @@
6
 
7
  """Skill Forge environment server components."""
8
 
9
- from .skill_forge_environment import SkillForgeEnvironment
 
 
 
10
 
11
  __all__ = ["SkillForgeEnvironment"]
 
6
 
7
  """Skill Forge environment server components."""
8
 
9
+ try:
10
+ from .environment import SkillForgeEnvironment
11
+ except ImportError:
12
+ from environment import SkillForgeEnvironment
13
 
14
  __all__ = ["SkillForgeEnvironment"]
server/app.py CHANGED
@@ -35,9 +35,12 @@ except Exception as e: # pragma: no cover
35
  "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
  ) from e
37
 
38
- # Import from local models.py (PYTHONPATH includes /app/env in Docker)
39
- from models import SkillForgeAction, SkillForgeObservation
40
- from .skill_forge_environment import SkillForgeEnvironment
 
 
 
41
 
42
 
43
  # Create the app with web interface and README integration
 
35
  "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
  ) from e
37
 
38
+ try:
39
+ from ..models import SkillForgeAction, SkillForgeObservation
40
+ from .environment import SkillForgeEnvironment
41
+ except ImportError:
42
+ from models import SkillForgeAction, SkillForgeObservation
43
+ from environment import SkillForgeEnvironment
44
 
45
 
46
  # Create the app with web interface and README integration
server/data_generator.py CHANGED
@@ -1,18 +1,403 @@
1
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  TASKS = [
 
4
  {
5
  "id": "A1",
6
- "cluster": "A", # never shown to agent
7
- "description": "Given a sales dataframe with columns [product, revenue, units], "
8
- "return the product names sorted by revenue descending.",
9
- "expected_skill": "sort_values",
10
- "dataframe": pd.DataFrame({
11
- "product": ["Widget", "Gadget", "Doohickey"],
12
- "revenue": [5000, 8000, 3000],
13
- "units": [100, 160, 60]
14
- }),
15
- "expected_output": ["Gadget", "Widget", "Doohickey"],
16
- },
17
- # ... 19 more
18
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
+ from datetime import datetime, timedelta
3
+
4
+ # ---------------------------------------------------------------------------
5
+ # Cluster A: filter → sort → extract
6
+ # ---------------------------------------------------------------------------
7
+
8
+ _A1_df = pd.DataFrame({
9
+ "product": ["Widget", "Gadget", "Doohickey", "Sprocket", "Thingamajig", "Gizmo"],
10
+ "revenue": [5000, 8000, 3000, 7500, 2000, 6000],
11
+ "region": ["West", "West", "East", "West", "East", "North"],
12
+ })
13
+
14
+ _A2_df = pd.DataFrame({
15
+ "name": ["Alice", "Bob", "Carol", "Dan", "Eve", "Frank", "Grace"],
16
+ "dept": ["Eng", "Sales", "Eng", "Eng", "HR", "Eng", "Sales"],
17
+ "tenure": [5, 3, 8, 2, 4, 10, 1],
18
+ })
19
+
20
+ _A3_df = pd.DataFrame({
21
+ "order_id": ["ORD-101", "ORD-102", "ORD-103", "ORD-104", "ORD-105", "ORD-106"],
22
+ "status": ["shipped", "pending", "shipped", "shipped", "cancelled", "shipped"],
23
+ "quantity": [50, 20, 80, 30, 10, 60],
24
+ })
25
+
26
+ _A4_df = pd.DataFrame({
27
+ "student_id": ["S01", "S02", "S03", "S04", "S05", "S06", "S07"],
28
+ "grade": ["A", "B", "A", "A", "C", "A", "B"],
29
+ "gpa": [3.9, 3.2, 3.95, 3.7, 2.8, 3.85, 3.1],
30
+ })
31
+
32
+ _A5_df = pd.DataFrame({
33
+ "item_name": ["Bolts", "Nails", "Screws", "Washers", "Rivets", "Pins"],
34
+ "stock": [5, 50, 8, 3, 100, 7],
35
+ "reorder_priority": [2, 10, 3, 1, 15, 4],
36
+ })
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Cluster B: normalize → filter → extract
40
+ # ---------------------------------------------------------------------------
41
+
42
+ _B1_df = pd.DataFrame({
43
+ "user_id": ["U1", "U2", "U3", "U4", "U5", "U6"],
44
+ "email": ["Alice@Gmail.COM", "bob@yahoo.com", "Carol@GMAIL.com",
45
+ "dan@gmail.COM", "eve@outlook.com", "frank@Gmail.com"],
46
+ })
47
+
48
+ _B2_df = pd.DataFrame({
49
+ "id": [1, 2, 3, 4, 5, 6, 7],
50
+ "name": [" Alice ", " Bob", " Andrew ", "Anna ", " Carl ", " Amy", " Brian "],
51
+ })
52
+
53
+ _B3_df = pd.DataFrame({
54
+ "user_id": ["U1", "U2", "U3", "U4", "U5", "U6"],
55
+ "country_code": ["us", "UK", "Us", "ca", "US", "us"],
56
+ })
57
+
58
+ _B4_df = pd.DataFrame({
59
+ "product_id": ["P1", "P2", "P3", "P4", "P5", "P6"],
60
+ "product_name": ["widget pro", "basic gadget", "pro sprocket",
61
+ "mega pro tool", "simple bolt", "pro widget x"],
62
+ })
63
+
64
+ _B5_df = pd.DataFrame({
65
+ "contact_id": ["C1", "C2", "C3", "C4", "C5", "C6"],
66
+ "phone": ["(555) 123-4567", "555.987.6543", "(555)111-2222",
67
+ "5551234", "555-999-8888", "(555) 000 1111"],
68
+ })
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Cluster C: date delta → filter → count
72
+ # ---------------------------------------------------------------------------
73
+
74
+ _today = datetime(2026, 3, 8)
75
+
76
+ _C1_df = pd.DataFrame({
77
+ "user_id": ["U1", "U2", "U3", "U4", "U5", "U6", "U7"],
78
+ "signup_date": [
79
+ _today - timedelta(days=10),
80
+ _today - timedelta(days=45),
81
+ _today - timedelta(days=5),
82
+ _today - timedelta(days=90),
83
+ _today - timedelta(days=25),
84
+ _today - timedelta(days=3),
85
+ _today - timedelta(days=60),
86
+ ],
87
+ "active": [True, True, True, False, True, True, False],
88
+ })
89
+
90
+ _C2_df = pd.DataFrame({
91
+ "order_id": ["O1", "O2", "O3", "O4", "O5", "O6"],
92
+ "order_date": [
93
+ _today - timedelta(days=2),
94
+ _today - timedelta(days=10),
95
+ _today - timedelta(days=5),
96
+ _today - timedelta(days=1),
97
+ _today - timedelta(days=14),
98
+ _today - timedelta(days=6),
99
+ ],
100
+ "amount": [100, 200, 150, 50, 300, 75],
101
+ })
102
+
103
+ _C3_df = pd.DataFrame({
104
+ "emp_id": ["E1", "E2", "E3", "E4", "E5", "E6"],
105
+ "hire_date": [
106
+ _today - timedelta(days=365),
107
+ _today - timedelta(days=900),
108
+ _today - timedelta(days=200),
109
+ _today - timedelta(days=500),
110
+ _today - timedelta(days=100),
111
+ _today - timedelta(days=1500),
112
+ ],
113
+ "dept": ["Eng", "Sales", "Eng", "HR", "Eng", "Sales"],
114
+ })
115
+
116
+ _C4_df = pd.DataFrame({
117
+ "event_id": ["EV1", "EV2", "EV3", "EV4", "EV5", "EV6"],
118
+ "event_date": [
119
+ _today + timedelta(days=5),
120
+ _today + timedelta(days=20),
121
+ _today + timedelta(days=10),
122
+ _today + timedelta(days=3),
123
+ _today + timedelta(days=30),
124
+ _today + timedelta(days=12),
125
+ ],
126
+ "venue": ["Hall A", "Hall B", "Hall A", "Hall C", "Hall B", "Hall A"],
127
+ })
128
+
129
+ _C5_df = pd.DataFrame({
130
+ "user_id": ["U1", "U2", "U3", "U4", "U5", "U6", "U7", "U8"],
131
+ "birthdate": [
132
+ _today - timedelta(days=365 * 20),
133
+ _today - timedelta(days=365 * 30),
134
+ _today - timedelta(days=365 * 22),
135
+ _today - timedelta(days=365 * 17),
136
+ _today - timedelta(days=365 * 19),
137
+ _today - timedelta(days=365 * 25),
138
+ _today - timedelta(days=365 * 24),
139
+ _today - timedelta(days=365 * 15),
140
+ ],
141
+ })
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Cluster D: groupby → aggregate → sort → slice
145
+ # ---------------------------------------------------------------------------
146
+
147
+ _D1_df = pd.DataFrame({
148
+ "region": ["West", "East", "West", "North", "East", "North", "West", "East", "South", "South"],
149
+ "revenue": [5000, 3000, 7000, 4000, 6000, 2000, 3000, 8000, 1000, 5000],
150
+ "product": ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A"],
151
+ })
152
+
153
+ _D2_df = pd.DataFrame({
154
+ "customer": ["Alice", "Bob", "Alice", "Carol", "Bob", "Alice",
155
+ "Carol", "Bob", "Alice", "Bob", "Carol", "Bob",
156
+ "Alice", "Bob"],
157
+ "order_id": [f"O{i}" for i in range(1, 15)],
158
+ "amount": [100, 50, 200, 150, 75, 300, 125, 80, 90, 60, 200, 45, 110, 95],
159
+ })
160
+
161
+ _D3_df = pd.DataFrame({
162
+ "dept": ["Eng", "Sales", "Eng", "HR", "Sales", "Eng", "HR", "Sales"],
163
+ "employee": ["A", "B", "C", "D", "E", "F", "G", "H"],
164
+ "salary": [120000, 80000, 110000, 70000, 90000, 130000, 75000, 85000],
165
+ })
166
+
167
+ _D4_df = pd.DataFrame({
168
+ "category": ["Electronics", "Clothing", "Electronics", "Food",
169
+ "Clothing", "Food", "Electronics", "Books", "Books"],
170
+ "product": ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9"],
171
+ "units_sold": [500, 200, 300, 150, 100, 400, 250, 50, 80],
172
+ })
173
+
174
+ _D5_df = pd.DataFrame({
175
+ "venue": ["Arena", "Hall", "Arena", "Park", "Hall", "Arena", "Park", "Hall"],
176
+ "event": ["E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8"],
177
+ "attendees": [500, 200, 300, 100, 250, 400, 150, 300],
178
+ "capacity": [1000, 600, 1000, 200, 600, 1000, 200, 600],
179
+ })
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # Compute expected outputs
184
+ # ---------------------------------------------------------------------------
185
+
186
+ # Cluster A
187
+ _A1_expected = _A1_df[_A1_df["region"] == "West"].sort_values("revenue", ascending=False)["product"].tolist()
188
+ _A2_expected = _A2_df[_A2_df["dept"] == "Eng"].sort_values("tenure", ascending=False)["name"].tolist()
189
+ _A3_expected = _A3_df[_A3_df["status"] == "shipped"].sort_values("quantity", ascending=False)["order_id"].tolist()
190
+ _A4_expected = _A4_df[_A4_df["grade"] == "A"].sort_values("gpa", ascending=False)["student_id"].tolist()
191
+ _A5_expected = _A5_df[_A5_df["stock"] < 10].sort_values("reorder_priority")["item_name"].tolist()
192
+
193
+ # Cluster B
194
+ _B1_expected = _B1_df.assign(email=_B1_df["email"].str.lower())\
195
+ .query("email.str.endswith('@gmail.com')")["email"].tolist()
196
+ _B2_expected = _B2_df.assign(name=_B2_df["name"].str.strip())\
197
+ .query("name.str.startswith('A')")["name"].tolist()
198
+ _B3_expected = _B3_df.assign(country_code=_B3_df["country_code"].str.upper())\
199
+ .query("country_code == 'US'")["user_id"].tolist()
200
+ _B4_expected = _B4_df.assign(product_name=_B4_df["product_name"].str.title())\
201
+ .query("product_name.str.contains('Pro')")["product_id"].tolist()
202
+ _B5_expected = _B5_df.assign(phone=_B5_df["phone"].str.replace(r"\D", "", regex=True))\
203
+ .query("phone.str.len() == 10")["phone"].tolist()
204
+
205
+ # Cluster C
206
+ _C1_expected = int(_C1_df.assign(days_since=(pd.Timestamp(_today) - _C1_df["signup_date"]).dt.days)\
207
+ .query("days_since < 30").shape[0])
208
+ _C2_expected = int(_C2_df.assign(order_age=(pd.Timestamp(_today) - _C2_df["order_date"]).dt.days)\
209
+ .query("order_age <= 7").shape[0])
210
+ _C3_expected = int(_C3_df.assign(tenure_years=(pd.Timestamp(_today) - _C3_df["hire_date"]).dt.days / 365)\
211
+ .query("tenure_years < 2").shape[0])
212
+ _C4_expected = int(_C4_df.assign(days_until=(_C4_df["event_date"] - pd.Timestamp(_today)).dt.days)\
213
+ .query("days_until <= 14").shape[0])
214
+ _C5_expected = int(_C5_df.assign(age=(pd.Timestamp(_today) - _C5_df["birthdate"]).dt.days / 365)\
215
+ .query("18 <= age <= 25").shape[0])
216
+
217
+ # Cluster D
218
+ _D1_expected = _D1_df.groupby("region")["revenue"].sum()\
219
+ .sort_values(ascending=False).head(3).index.tolist()
220
+ _D2_expected = _D2_df.groupby("customer")["order_id"].count()\
221
+ .loc[lambda x: x > 5].index.tolist()
222
+ _D3_expected = _D3_df.groupby("dept")["salary"].mean()\
223
+ .sort_values(ascending=False).index[0]
224
+ _D4_expected = _D4_df.groupby("category")["units_sold"].sum()\
225
+ .sort_values().head(2).index.tolist()
226
+ _D5_expected = _D5_df.assign(over=_D5_df["attendees"] > _D5_df["capacity"])\
227
+ .query("over").groupby("venue")["event"].count().index.tolist()
228
+ # D5 recompute: venues where total attendees > total capacity
229
+ _D5_agg = _D5_df.groupby("venue").agg({"attendees": "sum", "capacity": "first"}).reset_index()
230
+ _D5_expected = _D5_agg[_D5_agg["attendees"] > _D5_agg["capacity"]]["venue"].tolist()
231
+
232
+
233
+ # ---------------------------------------------------------------------------
234
+ # TASKS list
235
+ # ---------------------------------------------------------------------------
236
 
237
  TASKS = [
238
+ # --- Cluster A: filter → sort → extract ---
239
  {
240
  "id": "A1",
241
+ "cluster": "A",
242
+ "description": "Given a sales dataframe with columns [product, revenue, region], "
243
+ "return the product names for the West region sorted by revenue descending.",
244
+ "dataframe": _A1_df,
245
+ "expected_output": _A1_expected,
246
+ },
247
+ {
248
+ "id": "A2",
249
+ "cluster": "A",
250
+ "description": "Given an employees dataframe with columns [name, dept, tenure], "
251
+ "return the names of Engineering employees sorted by tenure descending.",
252
+ "dataframe": _A2_df,
253
+ "expected_output": _A2_expected,
254
+ },
255
+ {
256
+ "id": "A3",
257
+ "cluster": "A",
258
+ "description": "Given an orders dataframe with columns [order_id, status, quantity], "
259
+ "return the order IDs for shipped orders sorted by quantity descending.",
260
+ "dataframe": _A3_df,
261
+ "expected_output": _A3_expected,
262
+ },
263
+ {
264
+ "id": "A4",
265
+ "cluster": "A",
266
+ "description": "Given a students dataframe with columns [student_id, grade, gpa], "
267
+ "return the student IDs of students with grade A sorted by GPA descending.",
268
+ "dataframe": _A4_df,
269
+ "expected_output": _A4_expected,
270
+ },
271
+ {
272
+ "id": "A5",
273
+ "cluster": "A",
274
+ "description": "Given an inventory dataframe with columns [item_name, stock, reorder_priority], "
275
+ "return item names where stock is below 10, sorted by reorder priority ascending.",
276
+ "dataframe": _A5_df,
277
+ "expected_output": _A5_expected,
278
+ },
279
+ # --- Cluster B: normalize → filter → extract ---
280
+ {
281
+ "id": "B1",
282
+ "cluster": "B",
283
+ "description": "Given a users dataframe with columns [user_id, email], "
284
+ "lowercase all emails, keep only @gmail.com addresses, return the email list.",
285
+ "dataframe": _B1_df,
286
+ "expected_output": _B1_expected,
287
+ },
288
+ {
289
+ "id": "B2",
290
+ "cluster": "B",
291
+ "description": "Given a contacts dataframe with columns [id, name], "
292
+ "strip whitespace from names, keep names starting with 'A', return the name list.",
293
+ "dataframe": _B2_df,
294
+ "expected_output": _B2_expected,
295
+ },
296
+ {
297
+ "id": "B3",
298
+ "cluster": "B",
299
+ "description": "Given a users dataframe with columns [user_id, country_code], "
300
+ "uppercase all country codes, keep only 'US', return the user_id list.",
301
+ "dataframe": _B3_df,
302
+ "expected_output": _B3_expected,
303
+ },
304
+ {
305
+ "id": "B4",
306
+ "cluster": "B",
307
+ "description": "Given a products dataframe with columns [product_id, product_name], "
308
+ "title-case all product names, keep those containing 'Pro', return the product_id list.",
309
+ "dataframe": _B4_df,
310
+ "expected_output": _B4_expected,
311
+ },
312
+ {
313
+ "id": "B5",
314
+ "cluster": "B",
315
+ "description": "Given a contacts dataframe with columns [contact_id, phone], "
316
+ "remove all non-digit characters from phone numbers, keep only 10-digit ones, return the phone list.",
317
+ "dataframe": _B5_df,
318
+ "expected_output": _B5_expected,
319
+ },
320
+ # --- Cluster C: date delta → filter → count ---
321
+ {
322
+ "id": "C1",
323
+ "cluster": "C",
324
+ "description": "Given a users dataframe with columns [user_id, signup_date, active], "
325
+ "compute days since signup (from 2026-03-08), keep users who signed up within the last 30 days, return the count.",
326
+ "dataframe": _C1_df,
327
+ "expected_output": _C1_expected,
328
+ },
329
+ {
330
+ "id": "C2",
331
+ "cluster": "C",
332
+ "description": "Given an orders dataframe with columns [order_id, order_date, amount], "
333
+ "compute order age in days (from 2026-03-08), keep orders within the last 7 days, return the count.",
334
+ "dataframe": _C2_df,
335
+ "expected_output": _C2_expected,
336
+ },
337
+ {
338
+ "id": "C3",
339
+ "cluster": "C",
340
+ "description": "Given an employees dataframe with columns [emp_id, hire_date, dept], "
341
+ "compute tenure in years (from 2026-03-08), keep employees with less than 2 years, return the count.",
342
+ "dataframe": _C3_df,
343
+ "expected_output": _C3_expected,
344
+ },
345
+ {
346
+ "id": "C4",
347
+ "cluster": "C",
348
+ "description": "Given an events dataframe with columns [event_id, event_date, venue], "
349
+ "compute days until event (from 2026-03-08), keep events within the next 14 days, return the count.",
350
+ "dataframe": _C4_df,
351
+ "expected_output": _C4_expected,
352
+ },
353
+ {
354
+ "id": "C5",
355
+ "cluster": "C",
356
+ "description": "Given a users dataframe with columns [user_id, birthdate], "
357
+ "compute age in years (from 2026-03-08), keep users aged 18 to 25 inclusive, return the count.",
358
+ "dataframe": _C5_df,
359
+ "expected_output": _C5_expected,
360
+ },
361
+ # --- Cluster D: groupby → aggregate → sort → slice ---
362
+ {
363
+ "id": "D1",
364
+ "cluster": "D",
365
+ "description": "Given a sales dataframe with columns [region, revenue, product], "
366
+ "group by region, sum revenue, return the top 3 regions by total revenue.",
367
+ "dataframe": _D1_df,
368
+ "expected_output": _D1_expected,
369
+ },
370
+ {
371
+ "id": "D2",
372
+ "cluster": "D",
373
+ "description": "Given an orders dataframe with columns [customer, order_id, amount], "
374
+ "group by customer, count orders, return customers with more than 5 orders.",
375
+ "dataframe": _D2_df,
376
+ "expected_output": _D2_expected,
377
+ },
378
+ {
379
+ "id": "D3",
380
+ "cluster": "D",
381
+ "description": "Given an employees dataframe with columns [dept, employee, salary], "
382
+ "group by department, compute average salary, return the department with the highest average.",
383
+ "dataframe": _D3_df,
384
+ "expected_output": _D3_expected,
385
+ },
386
+ {
387
+ "id": "D4",
388
+ "cluster": "D",
389
+ "description": "Given a products dataframe with columns [category, product, units_sold], "
390
+ "group by category, sum units_sold, return the bottom 2 categories by total units.",
391
+ "dataframe": _D4_df,
392
+ "expected_output": _D4_expected,
393
+ },
394
+ {
395
+ "id": "D5",
396
+ "cluster": "D",
397
+ "description": "Given an events dataframe with columns [venue, event, attendees, capacity], "
398
+ "group by venue summing attendees and taking the first capacity, "
399
+ "return venues where total attendees exceed capacity.",
400
+ "dataframe": _D5_df,
401
+ "expected_output": _D5_expected,
402
+ },
403
+ ]
server/{skill_forge_environment.py → environment.py} RENAMED
@@ -10,6 +10,7 @@ Skill Forge Environment Implementation.
10
  An RL training environment where LLM Agents evolve from "reinventing the wheel" to "building a skill library."
11
  """
12
 
 
13
  import traceback
14
  from uuid import uuid4
15
 
@@ -18,139 +19,155 @@ import pandas as pd
18
  from openenv.core.env_server.interfaces import Environment
19
  from openenv.core.env_server.types import State
20
 
21
- from models import SkillForgeAction, SkillForgeObservation
22
- from .data_generator import TASKS
 
 
 
 
 
23
 
24
  class SkillForgeEnvironment(Environment):
25
  """
26
- A simple echo environment that echoes back messages.
27
-
28
- This environment is designed for testing the HTTP server infrastructure.
29
- It maintains minimal state and simply echoes back whatever message it receives.
30
-
31
- Example:
32
- >>> env = SkillForgeEnvironment()
33
- >>> obs = env.reset()
34
- >>> print(obs.echoed_message) # "Skill Forge environment ready!"
35
- >>>
36
- >>> obs = env.step(SkillForgeAction(message="Hello"))
37
- >>> print(obs.echoed_message) # "Hello"
38
- >>> print(obs.message_length) # 5
39
  """
40
 
41
- # Enable concurrent WebSocket sessions.
42
- # Set to True if your environment isolates state between instances.
43
- # When True, multiple WebSocket clients can connect simultaneously, each
44
- # getting their own environment instance (when using factory mode in app.py).
45
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
46
 
47
  def __init__(self):
48
- """Initialize the skill_forge environment."""
49
  self._state = State(episode_id=str(uuid4()), step_count=0)
50
- self._reset_count = 0
51
-
52
- self.skill_library = {}
53
- self.task_idx = 0
54
- self.action_history = []
55
- self.error_history = []
56
 
57
  def reset(self) -> SkillForgeObservation:
58
  """
59
- Reset the environment.
60
- skill_library intentionally NOT reset — persists across episodes
61
-
62
- Returns:
63
- SkillForgeObservation with a ready message
64
  """
65
  self._state = State(episode_id=str(uuid4()), step_count=0)
66
- self._reset_count += 1
67
-
68
  self.task_idx = 0
69
- task = TASKS[self.task_idx]
70
- self.action_history = []
71
- self.error_history = []
72
 
73
- return SkillForgeObservation(
74
- task_id=task["id"],
75
- task_description=task["description"],
76
- snapshot_data=task["dataframe"].head(5).to_string(),
77
- skill_library=self.skill_library,
78
- context="",
79
- step_count=0,
80
- total_tokens=0,
81
- result_correct=False,
82
- result_output="",
83
- expected_output=str(task["expected_output"]),
84
- )
85
 
86
- def step(self, action: SkillForgeAction) -> SkillForgeObservation:
87
- # TODO: create function _is_redundant
88
  self._state.step_count += 1
89
-
90
- if action.action_type not in ["create_skill", "use_skill", "raw_code"]:
91
- raise ValueError(f"Invalid action type: {action.action_type}")
92
-
93
  task = TASKS[self.task_idx]
94
- reward = 0.0
95
-
96
  if action.action_type == "create_skill":
 
 
 
97
  self.skill_library[action.skill_name] = {
98
  "template": action.content,
99
  "description": action.reasoning,
100
  "used_count": 0,
101
  }
102
- reward = 0.5 # TODO: revisit this value. Set it a bit high as we reward exploration
103
- result_correct = False
104
- result_output = f"Skill {action.skill_name} created"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  else:
 
 
 
 
 
 
 
 
 
 
 
106
  if action.action_type == "use_skill":
107
- skill = self.skill_library.get(action.content)
108
- # TODO: if action_type is use_skill while we don't have the skill yet, read reasoning to understand why the skill should be used and create the skill accordingly
109
- if skill:
110
- exec_code = skill["template"].format(**(action.params or {}))
111
- self.skill_library[action.content]["used_count"] += 1
112
- else: # TODO: log this scenario
113
- exec_code = None
114
- else:
115
- exec_code = action.code # TODO: add a penalty if we have a skill in skill lib for this problem
116
-
117
- # TODO: dataframe shouldn't be part of the task, the design is ugly
118
- result_correct, result_output = self._evaluate(exec_code, task["dataframe"], task["expected_output"])
119
- reward += 2.0 if result_correct else -1.0
120
- reward -= 0.001 * len(action.content) # token penalty
121
- if action.action_type == "use_skill" and result_correct:
122
- reward += 0.5 # reward for using a skill that worked
123
-
124
- # TODO P0: update the context with action history and error history
125
-
126
- # advance task
127
- self.task_idx = min(self.task_idx + 1, len(TASKS) - 1)
128
- done = self.task_idx == len(TASKS) - 1
129
- next_task = TASKS[self.task_idx]
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  return SkillForgeObservation(
132
- task_id=next_task["id"],
133
- task_description=next_task["description"],
134
- snapshot_data=next_task["dataframe"].head(5).to_string(),
135
  skill_library=self.skill_library,
136
  context="",
137
  step_count=self._state.step_count,
138
- total_tokens=0, # TODO P0: update this with the total tokens used
139
  result_correct=result_correct,
140
  result_output=result_output,
141
- expected_output=str(next_task["expected_output"]),
 
 
142
  )
143
-
144
- def _evaluate(self, exec_code, dataframe, expected_output):
145
- # TODO P0: implement this
146
- return True, "Evaluation successful"
147
 
148
  @property
149
  def state(self) -> State:
150
- """
151
- Get the current environment state.
152
-
153
- Returns:
154
- Current State with episode_id and step_count
155
- """
156
  return self._state
 
10
  An RL training environment where LLM Agents evolve from "reinventing the wheel" to "building a skill library."
11
  """
12
 
13
+ import json
14
  import traceback
15
  from uuid import uuid4
16
 
 
19
  from openenv.core.env_server.interfaces import Environment
20
  from openenv.core.env_server.types import State
21
 
22
+ try:
23
+ from ..models import SkillForgeAction, SkillForgeObservation
24
+ from .data_generator import TASKS
25
+ except ImportError:
26
+ from models import SkillForgeAction, SkillForgeObservation
27
+ from data_generator import TASKS
28
+
29
 
30
  class SkillForgeEnvironment(Environment):
31
  """
32
+ SkillForge RL environment.
33
+
34
+ The agent solves chained pandas tasks and can build a reusable skill library.
35
+ Skills persist across episodes so the agent can discover and reuse patterns.
 
 
 
 
 
 
 
 
 
36
  """
37
 
 
 
 
 
38
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
39
 
40
  def __init__(self):
 
41
  self._state = State(episode_id=str(uuid4()), step_count=0)
42
+ self.skill_library: dict = {}
43
+ self.task_idx: int = 0
44
+ self.tasks_solved: int = 0
45
+ self.total_tokens: int = 0
 
 
46
 
47
  def reset(self) -> SkillForgeObservation:
48
  """
49
+ Reset episode state. skill_library is NOT reset — persists across episodes.
 
 
 
 
50
  """
51
  self._state = State(episode_id=str(uuid4()), step_count=0)
 
 
52
  self.task_idx = 0
53
+ self.tasks_solved = 0
54
+ self.total_tokens = 0
 
55
 
56
+ task = TASKS[self.task_idx]
57
+ return self._make_observation(task, result_correct=False, result_output="", reward=0.0, done=False)
 
 
 
 
 
 
 
 
 
 
58
 
59
+ def step(self, action: SkillForgeAction) -> SkillForgeObservation:
 
60
  self._state.step_count += 1
 
 
 
 
61
  task = TASKS[self.task_idx]
62
+
63
+ # --- create_skill: store template, stay on current task ---
64
  if action.action_type == "create_skill":
65
+ token_cost = len(action.content)
66
+ self.total_tokens += token_cost
67
+
68
  self.skill_library[action.skill_name] = {
69
  "template": action.content,
70
  "description": action.reasoning,
71
  "used_count": 0,
72
  }
73
+ reward = 0.5
74
+ return self._make_observation(
75
+ task, result_correct=False,
76
+ result_output=f"Skill '{action.skill_name}' saved.",
77
+ reward=reward, done=False,
78
+ )
79
+
80
+ # --- use_skill or raw_code: execute and evaluate ---
81
+ if action.action_type == "use_skill":
82
+ skill = self.skill_library.get(action.content)
83
+ if skill is None:
84
+ # skill not found ��� treat as error
85
+ self.total_tokens += len(action.content)
86
+ return self._make_observation(
87
+ task, result_correct=False,
88
+ result_output=f"Skill '{action.content}' not found in library.",
89
+ reward=-0.3, done=False,
90
+ )
91
+ exec_code = skill["template"].format(**(action.params or {}))
92
+ skill["used_count"] += 1
93
+ # token cost for use_skill: skill name + serialized params (much shorter than full code)
94
+ skill_call_repr = action.content + json.dumps(action.params or {})
95
+ token_cost = len(skill_call_repr)
96
  else:
97
+ # raw_code
98
+ exec_code = action.content
99
+ token_cost = len(action.content)
100
+
101
+ self.total_tokens += token_cost
102
+
103
+ result_correct, result_output = self._evaluate(exec_code, task["dataframe"], task["expected_output"])
104
+
105
+ if result_correct:
106
+ reward = 2.0
107
+ reward -= 0.001 * token_cost
108
  if action.action_type == "use_skill":
109
+ reward += 0.5
110
+ self.tasks_solved += 1
111
+ self.task_idx += 1
112
+ else:
113
+ reward = -0.3
114
+
115
+ done = self.task_idx >= len(TASKS)
116
+ next_task = TASKS[self.task_idx] if not done else task
117
+
118
+ return self._make_observation(
119
+ next_task,
120
+ result_correct=result_correct,
121
+ result_output=result_output,
122
+ reward=reward,
123
+ done=done,
124
+ )
 
 
 
 
 
 
 
125
 
126
+ def _evaluate(self, exec_code: str | None, dataframe: pd.DataFrame, expected_output) -> tuple[bool, str]:
127
+ if exec_code is None:
128
+ return False, "No code to execute."
129
+ try:
130
+ namespace = {"df": dataframe.copy(), "pd": pd, "__builtins__": {"len": len, "str": str, "int": int, "float": float, "list": list, "dict": dict, "bool": bool, "range": range, "abs": abs, "min": min, "max": max, "sum": sum, "sorted": sorted, "round": round, "True": True, "False": False, "None": None}}
131
+ result = eval(exec_code, namespace)
132
+
133
+ # normalize for comparison
134
+ if isinstance(result, pd.DataFrame):
135
+ result = result.values.tolist()
136
+ if isinstance(result, pd.Series):
137
+ result = result.tolist()
138
+ if isinstance(result, pd.Index):
139
+ result = result.tolist()
140
+
141
+ expected = expected_output
142
+ if isinstance(expected, pd.Series):
143
+ expected = expected.tolist()
144
+
145
+ try:
146
+ is_correct = result == expected
147
+ except (ValueError, TypeError):
148
+ is_correct = False
149
+
150
+ return bool(is_correct), str(result)
151
+ except Exception:
152
+ return False, traceback.format_exc()
153
+
154
+ def _make_observation(self, task: dict, result_correct: bool, result_output: str,
155
+ reward: float, done: bool) -> SkillForgeObservation:
156
  return SkillForgeObservation(
157
+ task_id=task["id"],
158
+ task_description=task["description"],
159
+ snapshot_data=task["dataframe"].head(5).to_string(),
160
  skill_library=self.skill_library,
161
  context="",
162
  step_count=self._state.step_count,
163
+ total_tokens=self.total_tokens,
164
  result_correct=result_correct,
165
  result_output=result_output,
166
+ expected_output=str(task["expected_output"]),
167
+ reward=reward,
168
+ done=done,
169
  )
 
 
 
 
170
 
171
  @property
172
  def state(self) -> State:
 
 
 
 
 
 
173
  return self._state
server/requirements.txt CHANGED
@@ -1,6 +1,4 @@
1
- openenv[core]>=0.2.0
2
  fastapi>=0.115.0
3
  uvicorn>=0.24.0
4
-
5
-
6
-
 
1
+ openenv-core[core]>=0.2.0
2
  fastapi>=0.115.0
3
  uvicorn>=0.24.0
4
+ pandas>=2.3.3