synth-ai 0.2.2.dev0__py3-none-any.whl → 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- synth_ai/cli/__init__.py +66 -0
- synth_ai/cli/balance.py +205 -0
- synth_ai/cli/calc.py +70 -0
- synth_ai/cli/demo.py +74 -0
- synth_ai/{cli.py → cli/legacy_root_backup.py} +60 -15
- synth_ai/cli/man.py +103 -0
- synth_ai/cli/recent.py +126 -0
- synth_ai/cli/root.py +184 -0
- synth_ai/cli/status.py +126 -0
- synth_ai/cli/traces.py +136 -0
- synth_ai/cli/watch.py +508 -0
- synth_ai/config/base_url.py +53 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/analyze_semantic_words_markdown.py +252 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_traces_sft_duckdb_v2_backup.py +413 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_traces_sft_turso.py +646 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/kick_off_ft_synth.py +34 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/test_crafter_react_agent_lm_synth.py +1740 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/test_crafter_react_agent_lm_synth_v2_backup.py +1318 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/filter_traces_sft_duckdb_v2_backup.py +386 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/filter_traces_sft_turso.py +580 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/run_rollouts_for_models_and_compare_v2_backup.py +1352 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/test_crafter_react_agent_openai_v2_backup.py +2551 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_trace_evaluation.py +1 -1
- synth_ai/environments/examples/crafter_classic/agent_demos/old/traces/session_crafter_episode_16_15227b68-2906-416f-acc4-d6a9b4fa5828_20250725_001154.json +1363 -1
- synth_ai/environments/examples/crafter_classic/agent_demos/test_crafter_react_agent.py +3 -3
- synth_ai/environments/examples/enron/dataset/corbt___enron_emails_sample_questions/default/0.0.0/293c9fe8170037e01cc9cf5834e0cd5ef6f1a6bb/dataset_info.json +1 -0
- synth_ai/environments/examples/nethack/helpers/achievements.json +64 -0
- synth_ai/environments/examples/red/units/test_exploration_strategy.py +1 -1
- synth_ai/environments/examples/red/units/test_menu_bug_reproduction.py +5 -5
- synth_ai/environments/examples/red/units/test_movement_debug.py +2 -2
- synth_ai/environments/examples/red/units/test_retry_movement.py +1 -1
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/available_envs.json +122 -0
- synth_ai/environments/examples/sokoban/verified_puzzles.json +54987 -0
- synth_ai/experimental/synth_oss.py +446 -0
- synth_ai/learning/core.py +21 -0
- synth_ai/learning/gateway.py +4 -0
- synth_ai/learning/prompts/mipro.py +0 -0
- synth_ai/lm/__init__.py +3 -0
- synth_ai/lm/core/main.py +4 -0
- synth_ai/lm/core/main_v3.py +68 -13
- synth_ai/lm/core/vendor_clients.py +4 -0
- synth_ai/lm/provider_support/openai.py +11 -2
- synth_ai/lm/vendors/base.py +7 -0
- synth_ai/lm/vendors/openai_standard.py +339 -4
- synth_ai/lm/vendors/openai_standard_responses.py +243 -0
- synth_ai/lm/vendors/synth_client.py +155 -5
- synth_ai/lm/warmup.py +54 -17
- synth_ai/tracing/__init__.py +18 -0
- synth_ai/tracing_v1/__init__.py +29 -14
- synth_ai/tracing_v3/config.py +13 -7
- synth_ai/tracing_v3/db_config.py +6 -6
- synth_ai/tracing_v3/turso/manager.py +8 -8
- synth_ai/tui/__main__.py +13 -0
- synth_ai/tui/dashboard.py +329 -0
- synth_ai/v0/tracing/__init__.py +0 -0
- synth_ai/{tracing → v0/tracing}/base_client.py +3 -3
- synth_ai/{tracing → v0/tracing}/client_manager.py +1 -1
- synth_ai/{tracing → v0/tracing}/context.py +1 -1
- synth_ai/{tracing → v0/tracing}/decorators.py +11 -11
- synth_ai/v0/tracing/events/__init__.py +0 -0
- synth_ai/{tracing → v0/tracing}/events/manage.py +4 -4
- synth_ai/{tracing → v0/tracing}/events/scope.py +6 -6
- synth_ai/{tracing → v0/tracing}/events/store.py +3 -3
- synth_ai/{tracing → v0/tracing}/immediate_client.py +6 -6
- synth_ai/{tracing → v0/tracing}/log_client_base.py +2 -2
- synth_ai/{tracing → v0/tracing}/retry_queue.py +3 -3
- synth_ai/{tracing → v0/tracing}/trackers.py +2 -2
- synth_ai/{tracing → v0/tracing}/upload.py +4 -4
- synth_ai/v0/tracing_v1/__init__.py +16 -0
- synth_ai/{tracing_v1 → v0/tracing_v1}/base_client.py +3 -3
- synth_ai/{tracing_v1 → v0/tracing_v1}/client_manager.py +1 -1
- synth_ai/{tracing_v1 → v0/tracing_v1}/context.py +1 -1
- synth_ai/{tracing_v1 → v0/tracing_v1}/decorators.py +11 -11
- synth_ai/v0/tracing_v1/events/__init__.py +0 -0
- synth_ai/{tracing_v1 → v0/tracing_v1}/events/manage.py +4 -4
- synth_ai/{tracing_v1 → v0/tracing_v1}/events/scope.py +6 -6
- synth_ai/{tracing_v1 → v0/tracing_v1}/events/store.py +3 -3
- synth_ai/{tracing_v1 → v0/tracing_v1}/immediate_client.py +6 -6
- synth_ai/{tracing_v1 → v0/tracing_v1}/log_client_base.py +2 -2
- synth_ai/{tracing_v1 → v0/tracing_v1}/retry_queue.py +3 -3
- synth_ai/{tracing_v1 → v0/tracing_v1}/trackers.py +2 -2
- synth_ai/{tracing_v1 → v0/tracing_v1}/upload.py +4 -4
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/METADATA +98 -4
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/RECORD +98 -62
- /synth_ai/{tracing/events/__init__.py → environments/examples/crafter_classic/debug_translation.py} +0 -0
- /synth_ai/{tracing_v1/events/__init__.py → learning/prompts/gepa.py} +0 -0
- /synth_ai/{tracing → v0/tracing}/abstractions.py +0 -0
- /synth_ai/{tracing → v0/tracing}/config.py +0 -0
- /synth_ai/{tracing → v0/tracing}/local.py +0 -0
- /synth_ai/{tracing → v0/tracing}/utils.py +0 -0
- /synth_ai/{tracing_v1 → v0/tracing_v1}/abstractions.py +0 -0
- /synth_ai/{tracing_v1 → v0/tracing_v1}/config.py +0 -0
- /synth_ai/{tracing_v1 → v0/tracing_v1}/local.py +0 -0
- /synth_ai/{tracing_v1 → v0/tracing_v1}/utils.py +0 -0
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/WHEEL +0 -0
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/entry_points.txt +0 -0
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/licenses/LICENSE +0 -0
- {synth_ai-0.2.2.dev0.dist-info → synth_ai-0.2.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,646 @@
|
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
"""
|
3
|
+
Filter traces from Turso/SQLite (v3) to create Modal/Synth SFT-ready .jsonl files
|
4
|
+
Supports two modes:
|
5
|
+
1. Trajectory-level filtering: Include entire trajectories above a score threshold
|
6
|
+
2. Window-based filtering: Extract high-scoring windows of actions
|
7
|
+
|
8
|
+
This is the v3 version using the new async Turso-based tracing system.
|
9
|
+
"""
|
10
|
+
|
11
|
+
import json
|
12
|
+
import argparse
|
13
|
+
import asyncio
|
14
|
+
from pathlib import Path
|
15
|
+
from typing import List, Dict, Any, Tuple, Optional
|
16
|
+
from collections import defaultdict
|
17
|
+
import numpy as np
|
18
|
+
import os
|
19
|
+
import sys
|
20
|
+
import toml
|
21
|
+
import pandas as pd
|
22
|
+
|
23
|
+
# Add synth_ai to path
|
24
|
+
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent.parent.parent))
|
25
|
+
|
26
|
+
from synth_ai.tracing_v3 import SessionTracer
|
27
|
+
from synth_ai.tracing_v3.turso.manager import AsyncSQLTraceManager
|
28
|
+
from synth_ai.tracing_v3.abstractions import LMCAISEvent, EnvironmentEvent, RuntimeEvent
|
29
|
+
|
30
|
+
|
31
|
+
def create_histogram(data: List[float], bins: int = 20, width: int = 60, height: int = 15,
|
32
|
+
title: str = "", x_label: str = "", y_label: str = "") -> str:
|
33
|
+
"""Create a beautiful ASCII histogram."""
|
34
|
+
if not data:
|
35
|
+
return "No data to display"
|
36
|
+
|
37
|
+
# Create histogram
|
38
|
+
counts, edges = np.histogram(data, bins=bins)
|
39
|
+
max_count = max(counts) if len(counts) > 0 else 1
|
40
|
+
|
41
|
+
# Normalize heights
|
42
|
+
if max_count > 0:
|
43
|
+
heights = [int(c * height / max_count) for c in counts]
|
44
|
+
else:
|
45
|
+
heights = [0] * len(counts)
|
46
|
+
|
47
|
+
# Build the plot
|
48
|
+
lines = []
|
49
|
+
|
50
|
+
# Title
|
51
|
+
if title:
|
52
|
+
lines.append(f"\n{title.center(width + 10)}")
|
53
|
+
lines.append("=" * (width + 10))
|
54
|
+
|
55
|
+
# Y-axis label
|
56
|
+
if y_label:
|
57
|
+
lines.append(f"{y_label}")
|
58
|
+
|
59
|
+
# Plot area with y-axis
|
60
|
+
for y in range(height, 0, -1):
|
61
|
+
# Y-axis value
|
62
|
+
y_val = int(max_count * y / height)
|
63
|
+
line = f"{y_val:>6} │"
|
64
|
+
|
65
|
+
# Bars
|
66
|
+
for h in heights:
|
67
|
+
if h >= y:
|
68
|
+
line += "█"
|
69
|
+
else:
|
70
|
+
line += " "
|
71
|
+
|
72
|
+
lines.append(line)
|
73
|
+
|
74
|
+
# X-axis
|
75
|
+
lines.append(f"{'':>6} └" + "─" * len(heights))
|
76
|
+
|
77
|
+
# X-axis labels
|
78
|
+
x_labels_line = " " * 8
|
79
|
+
min_val, max_val = min(data), max(data)
|
80
|
+
|
81
|
+
# Add labels at key positions
|
82
|
+
label_positions = [0, len(heights)//4, len(heights)//2, 3*len(heights)//4, len(heights)-1]
|
83
|
+
for i, pos in enumerate(label_positions):
|
84
|
+
if pos < len(edges) - 1:
|
85
|
+
val = edges[pos]
|
86
|
+
label = f"{val:.1f}"
|
87
|
+
# Calculate position
|
88
|
+
target_pos = 8 + pos
|
89
|
+
if i == 0:
|
90
|
+
x_labels_line = label + x_labels_line[len(label):]
|
91
|
+
elif i == len(label_positions) - 1:
|
92
|
+
start = max(0, target_pos - len(label))
|
93
|
+
x_labels_line = x_labels_line[:start] + label
|
94
|
+
else:
|
95
|
+
start = max(0, target_pos - len(label)//2)
|
96
|
+
end = min(len(x_labels_line), start + len(label))
|
97
|
+
if start < len(x_labels_line):
|
98
|
+
x_labels_line = x_labels_line[:start] + label[:end-start] + x_labels_line[end:]
|
99
|
+
|
100
|
+
lines.append(x_labels_line)
|
101
|
+
|
102
|
+
# X-axis label
|
103
|
+
if x_label:
|
104
|
+
lines.append(f"\n{x_label.center(width + 10)}")
|
105
|
+
|
106
|
+
return "\n".join(lines)
|
107
|
+
|
108
|
+
|
109
|
+
def create_bar_chart(categories: List[str], values: List[int], width: int = 60,
|
110
|
+
title: str = "", show_values: bool = True) -> str:
|
111
|
+
"""Create a horizontal bar chart."""
|
112
|
+
if not categories or not values:
|
113
|
+
return "No data to display"
|
114
|
+
|
115
|
+
max_val = max(values) if values else 1
|
116
|
+
lines = []
|
117
|
+
|
118
|
+
# Title
|
119
|
+
if title:
|
120
|
+
lines.append(f"\n{title}")
|
121
|
+
lines.append("=" * (width + 20))
|
122
|
+
|
123
|
+
# Find longest category name for alignment
|
124
|
+
max_cat_len = max(len(cat) for cat in categories)
|
125
|
+
|
126
|
+
# Create bars
|
127
|
+
for cat, val in zip(categories, values):
|
128
|
+
# Normalize bar length
|
129
|
+
bar_len = int(val * width / max_val) if max_val > 0 else 0
|
130
|
+
bar = "█" * bar_len
|
131
|
+
|
132
|
+
# Format line
|
133
|
+
if show_values:
|
134
|
+
line = f"{cat:<{max_cat_len}} │ {bar} {val}"
|
135
|
+
else:
|
136
|
+
line = f"{cat:<{max_cat_len}} │ {bar}"
|
137
|
+
|
138
|
+
lines.append(line)
|
139
|
+
|
140
|
+
return "\n".join(lines)
|
141
|
+
|
142
|
+
|
143
|
+
class FinetuningDataExtractorV3:
|
144
|
+
"""Extract fine-tuning data from v3 Turso traces."""
|
145
|
+
|
146
|
+
def __init__(self, db_url: str):
|
147
|
+
self.db_manager = AsyncSQLTraceManager(db_url)
|
148
|
+
self._initialized = False
|
149
|
+
|
150
|
+
async def __aenter__(self):
|
151
|
+
await self.db_manager.initialize()
|
152
|
+
self._initialized = True
|
153
|
+
return self
|
154
|
+
|
155
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
156
|
+
await self.db_manager.close()
|
157
|
+
|
158
|
+
async def get_all_sessions(self) -> pd.DataFrame:
|
159
|
+
"""Get all session IDs from the database."""
|
160
|
+
query = """
|
161
|
+
SELECT DISTINCT session_id, created_at
|
162
|
+
FROM session_traces
|
163
|
+
ORDER BY created_at DESC
|
164
|
+
"""
|
165
|
+
return await self.db_manager.query_traces(query)
|
166
|
+
|
167
|
+
async def get_session_metrics(self, session_id: str) -> Dict[str, Any]:
|
168
|
+
"""Get metrics for a specific session."""
|
169
|
+
# Get total reward from environment events
|
170
|
+
# Now that rewards are properly saved in the DB, we can use them directly
|
171
|
+
reward_query = """
|
172
|
+
SELECT COALESCE(SUM(reward), 0) as total_reward
|
173
|
+
FROM events
|
174
|
+
WHERE session_id = :session_id
|
175
|
+
AND event_type = 'environment'
|
176
|
+
AND reward IS NOT NULL
|
177
|
+
"""
|
178
|
+
reward_df = await self.db_manager.query_traces(reward_query, {"session_id": session_id})
|
179
|
+
total_reward = float(reward_df['total_reward'].iloc[0]) if not reward_df.empty else 0.0
|
180
|
+
|
181
|
+
# Get total tokens and cost from LM events
|
182
|
+
lm_query = """
|
183
|
+
SELECT
|
184
|
+
COALESCE(SUM(total_tokens), 0) as total_tokens,
|
185
|
+
COALESCE(SUM(cost_usd) / 100.0, 0) as total_cost
|
186
|
+
FROM events
|
187
|
+
WHERE session_id = :session_id
|
188
|
+
AND event_type = 'cais'
|
189
|
+
"""
|
190
|
+
lm_df = await self.db_manager.query_traces(lm_query, {"session_id": session_id})
|
191
|
+
|
192
|
+
total_tokens = int(lm_df['total_tokens'].iloc[0]) if not lm_df.empty else 0
|
193
|
+
total_cost = float(lm_df['total_cost'].iloc[0]) if not lm_df.empty else 0.0
|
194
|
+
|
195
|
+
return {
|
196
|
+
'session_id': session_id,
|
197
|
+
'total_reward': total_reward,
|
198
|
+
'total_tokens': total_tokens,
|
199
|
+
'total_cost': total_cost
|
200
|
+
}
|
201
|
+
|
202
|
+
async def get_session_achievements(self, session_id: str) -> List[str]:
|
203
|
+
"""Get list of achievements unlocked in a session."""
|
204
|
+
# Look for achievement events in environment data
|
205
|
+
# In v3, system_state_after is a direct column
|
206
|
+
query = """
|
207
|
+
SELECT system_state_after
|
208
|
+
FROM events
|
209
|
+
WHERE session_id = :session_id
|
210
|
+
AND event_type = 'environment'
|
211
|
+
AND system_state_after IS NOT NULL
|
212
|
+
ORDER BY id DESC
|
213
|
+
LIMIT 1
|
214
|
+
"""
|
215
|
+
df = await self.db_manager.query_traces(query, {"session_id": session_id})
|
216
|
+
|
217
|
+
if df.empty:
|
218
|
+
return []
|
219
|
+
|
220
|
+
try:
|
221
|
+
# Parse the system_state_after JSON
|
222
|
+
state_after = df['system_state_after'].iloc[0]
|
223
|
+
if state_after:
|
224
|
+
# If it's a string, parse it
|
225
|
+
if isinstance(state_after, str):
|
226
|
+
state_after = json.loads(state_after)
|
227
|
+
|
228
|
+
# Look for achievements in public_state
|
229
|
+
if isinstance(state_after, dict) and 'public_state' in state_after:
|
230
|
+
public_state = state_after['public_state']
|
231
|
+
if 'achievements_status' in public_state:
|
232
|
+
achievements = public_state['achievements_status']
|
233
|
+
# Return list of unlocked achievements
|
234
|
+
return [k for k, v in achievements.items() if v]
|
235
|
+
except Exception as e:
|
236
|
+
print(f"Error parsing achievements: {e}")
|
237
|
+
pass
|
238
|
+
|
239
|
+
return []
|
240
|
+
|
241
|
+
async def filter_by_achievements(self, min_achievements: int) -> List[str]:
|
242
|
+
"""Get sessions with at least min_achievements unlocked."""
|
243
|
+
all_sessions = await self.get_all_sessions()
|
244
|
+
qualifying_sessions = []
|
245
|
+
|
246
|
+
for _, row in all_sessions.iterrows():
|
247
|
+
session_id = row['session_id']
|
248
|
+
achievements = await self.get_session_achievements(session_id)
|
249
|
+
if len(achievements) >= min_achievements:
|
250
|
+
qualifying_sessions.append(session_id)
|
251
|
+
|
252
|
+
return qualifying_sessions
|
253
|
+
|
254
|
+
async def extract_openai_format(self, session_ids: List[str], min_reward: float = 0.0) -> List[Dict[str, Any]]:
|
255
|
+
"""Extract training data in OpenAI format from filtered sessions."""
|
256
|
+
training_data = []
|
257
|
+
|
258
|
+
for session_id in session_ids:
|
259
|
+
# Get messages directly from the messages table
|
260
|
+
messages_query = """
|
261
|
+
SELECT m.message_type, m.content, m.message_time, st.turn_number
|
262
|
+
FROM messages m
|
263
|
+
LEFT JOIN session_timesteps st ON m.timestep_id = st.id
|
264
|
+
WHERE m.session_id = :session_id
|
265
|
+
ORDER BY COALESCE(st.turn_number, m.message_time), m.id
|
266
|
+
"""
|
267
|
+
|
268
|
+
messages_df = await self.db_manager.query_traces(messages_query, {"session_id": session_id})
|
269
|
+
|
270
|
+
if len(messages_df) == 0:
|
271
|
+
continue
|
272
|
+
|
273
|
+
# Build conversation history
|
274
|
+
messages = []
|
275
|
+
system_message = None
|
276
|
+
|
277
|
+
for _, row in messages_df.iterrows():
|
278
|
+
msg_type = row['message_type']
|
279
|
+
content = row['content']
|
280
|
+
|
281
|
+
# Parse content if it's JSON (from origin_system_id format)
|
282
|
+
try:
|
283
|
+
import json
|
284
|
+
content_data = json.loads(content)
|
285
|
+
if isinstance(content_data, dict) and 'payload' in content_data:
|
286
|
+
content = content_data['payload']
|
287
|
+
except:
|
288
|
+
pass
|
289
|
+
|
290
|
+
if msg_type == 'system' and system_message is None:
|
291
|
+
# Extract system message from the first system message
|
292
|
+
if isinstance(content, str):
|
293
|
+
system_message = content
|
294
|
+
|
295
|
+
elif msg_type == 'user':
|
296
|
+
# Format user messages
|
297
|
+
if isinstance(content, dict):
|
298
|
+
# Convert observation dict to formatted string
|
299
|
+
content = self._format_observation_content(content)
|
300
|
+
messages.append({"role": "user", "content": str(content)})
|
301
|
+
|
302
|
+
elif msg_type == 'assistant':
|
303
|
+
messages.append({"role": "assistant", "content": str(content)})
|
304
|
+
|
305
|
+
# Add system message at the beginning if found
|
306
|
+
if system_message:
|
307
|
+
messages.insert(0, {"role": "system", "content": system_message})
|
308
|
+
|
309
|
+
# Only include if we have a complete conversation
|
310
|
+
if len(messages) > 1:
|
311
|
+
# Get total reward for this session
|
312
|
+
reward_query = """
|
313
|
+
SELECT COALESCE(SUM(reward), 0) as total_reward
|
314
|
+
FROM events
|
315
|
+
WHERE session_id = :session_id
|
316
|
+
AND event_type = 'environment'
|
317
|
+
AND reward IS NOT NULL
|
318
|
+
"""
|
319
|
+
reward_df = await self.db_manager.query_traces(reward_query, {"session_id": session_id})
|
320
|
+
total_reward = reward_df.iloc[0]['total_reward'] if len(reward_df) > 0 else 0
|
321
|
+
|
322
|
+
training_data.append({
|
323
|
+
"messages": messages,
|
324
|
+
"metadata": {
|
325
|
+
"session_id": session_id,
|
326
|
+
"total_reward": float(total_reward) # Convert to float for JSON serialization
|
327
|
+
}
|
328
|
+
})
|
329
|
+
|
330
|
+
return training_data
|
331
|
+
|
332
|
+
def _format_observation_content(self, obs: Dict[str, Any]) -> str:
|
333
|
+
"""Format observation dict into a readable string."""
|
334
|
+
if not isinstance(obs, dict):
|
335
|
+
return str(obs)
|
336
|
+
|
337
|
+
# Extract key fields for a concise representation
|
338
|
+
parts = []
|
339
|
+
|
340
|
+
if 'inventory' in obs:
|
341
|
+
inv = obs['inventory']
|
342
|
+
inv_str = ", ".join([f"{k}: {v}" for k, v in inv.items() if v > 0])
|
343
|
+
if inv_str:
|
344
|
+
parts.append(f"Inventory: {inv_str}")
|
345
|
+
|
346
|
+
if 'achievements_status' in obs:
|
347
|
+
achievements = [k for k, v in obs['achievements_status'].items() if v]
|
348
|
+
if achievements:
|
349
|
+
parts.append(f"Achievements: {', '.join(achievements)}")
|
350
|
+
|
351
|
+
if 'health' in obs:
|
352
|
+
parts.append(f"Health: {obs.get('health', 0)}")
|
353
|
+
|
354
|
+
return "; ".join(parts) if parts else "Empty observation"
|
355
|
+
|
356
|
+
|
357
|
+
async def filter_traces_from_turso(
|
358
|
+
db_url: str,
|
359
|
+
output_path: str,
|
360
|
+
config: Dict[str, Any]
|
361
|
+
) -> Tuple[int, Dict[str, Any]]:
|
362
|
+
"""
|
363
|
+
Filter traces from Turso/SQLite v3 database based on configuration.
|
364
|
+
|
365
|
+
Returns:
|
366
|
+
Tuple of (num_examples, statistics_dict)
|
367
|
+
"""
|
368
|
+
mode = config.get("mode", "trajectory")
|
369
|
+
filters = config.get("filters", {})
|
370
|
+
|
371
|
+
# Extract filtering parameters
|
372
|
+
min_reward = filters.get("min_total_reward", 0.0)
|
373
|
+
min_achievements = filters.get("min_achievements", 0)
|
374
|
+
max_cost = filters.get("max_cost", float('inf'))
|
375
|
+
max_tokens = filters.get("max_tokens", float('inf'))
|
376
|
+
|
377
|
+
# Modal/Synth specific: filter by model if specified
|
378
|
+
target_models = filters.get("models", [])
|
379
|
+
|
380
|
+
statistics = {
|
381
|
+
"total_sessions": 0,
|
382
|
+
"filtered_sessions": 0,
|
383
|
+
"total_examples": 0,
|
384
|
+
"reward_distribution": [],
|
385
|
+
"token_distribution": [],
|
386
|
+
"cost_distribution": [],
|
387
|
+
"model_distribution": defaultdict(int)
|
388
|
+
}
|
389
|
+
|
390
|
+
async with FinetuningDataExtractorV3(db_url) as extractor:
|
391
|
+
# Get all sessions
|
392
|
+
all_sessions = await extractor.get_all_sessions()
|
393
|
+
statistics["total_sessions"] = len(all_sessions)
|
394
|
+
|
395
|
+
# Filter sessions based on criteria
|
396
|
+
filtered_sessions = []
|
397
|
+
|
398
|
+
for _, row in all_sessions.iterrows():
|
399
|
+
session_id = row['session_id']
|
400
|
+
metrics = await extractor.get_session_metrics(session_id)
|
401
|
+
|
402
|
+
# Apply filters
|
403
|
+
if metrics['total_reward'] < min_reward:
|
404
|
+
continue
|
405
|
+
if metrics['total_cost'] > max_cost:
|
406
|
+
continue
|
407
|
+
if metrics['total_tokens'] > max_tokens:
|
408
|
+
continue
|
409
|
+
|
410
|
+
# Check achievements if required
|
411
|
+
if min_achievements > 0:
|
412
|
+
achievements = await extractor.get_session_achievements(session_id)
|
413
|
+
if len(achievements) < min_achievements:
|
414
|
+
continue
|
415
|
+
|
416
|
+
# Check model filter if specified
|
417
|
+
if target_models:
|
418
|
+
model_query = """
|
419
|
+
SELECT DISTINCT model_name
|
420
|
+
FROM events
|
421
|
+
WHERE session_id = :session_id
|
422
|
+
AND event_type = 'cais'
|
423
|
+
AND model_name IS NOT NULL
|
424
|
+
"""
|
425
|
+
model_df = await extractor.db_manager.query_traces(
|
426
|
+
model_query, {"session_id": session_id}
|
427
|
+
)
|
428
|
+
session_models = model_df['model_name'].tolist() if not model_df.empty else []
|
429
|
+
if not any(model in target_models for model in session_models):
|
430
|
+
continue
|
431
|
+
|
432
|
+
filtered_sessions.append(session_id)
|
433
|
+
|
434
|
+
# Collect statistics
|
435
|
+
statistics["reward_distribution"].append(metrics['total_reward'])
|
436
|
+
statistics["token_distribution"].append(metrics['total_tokens'])
|
437
|
+
statistics["cost_distribution"].append(metrics['total_cost'])
|
438
|
+
|
439
|
+
statistics["filtered_sessions"] = len(filtered_sessions)
|
440
|
+
|
441
|
+
# Extract training data
|
442
|
+
if mode == "trajectory":
|
443
|
+
training_data = await extractor.extract_openai_format(
|
444
|
+
session_ids=filtered_sessions,
|
445
|
+
min_reward=min_reward
|
446
|
+
)
|
447
|
+
else: # window mode
|
448
|
+
# For window mode, we need to implement window extraction
|
449
|
+
# For now, use trajectory mode
|
450
|
+
training_data = await extractor.extract_openai_format(
|
451
|
+
session_ids=filtered_sessions,
|
452
|
+
min_reward=min_reward
|
453
|
+
)
|
454
|
+
|
455
|
+
statistics["total_examples"] = len(training_data)
|
456
|
+
|
457
|
+
# Write to output file
|
458
|
+
output_file = Path(output_path)
|
459
|
+
output_file.parent.mkdir(exist_ok=True)
|
460
|
+
|
461
|
+
with open(output_file, 'w') as f:
|
462
|
+
for example in training_data:
|
463
|
+
f.write(json.dumps(example) + '\n')
|
464
|
+
|
465
|
+
# Get model distribution
|
466
|
+
model_query = """
|
467
|
+
SELECT model_name, COUNT(*) as count
|
468
|
+
FROM events
|
469
|
+
WHERE event_type = 'cais'
|
470
|
+
AND model_name IS NOT NULL
|
471
|
+
GROUP BY model_name
|
472
|
+
"""
|
473
|
+
model_stats = await extractor.db_manager.query_traces(model_query)
|
474
|
+
for _, row in model_stats.iterrows():
|
475
|
+
statistics["model_distribution"][row['model_name']] = int(row['count'])
|
476
|
+
|
477
|
+
return len(training_data), statistics
|
478
|
+
|
479
|
+
|
480
|
+
def print_statistics(stats: Dict[str, Any]):
|
481
|
+
"""Print filtering statistics with visualizations."""
|
482
|
+
print("\n" + "="*80)
|
483
|
+
print("FILTERING STATISTICS (Modal/Synth - v3)")
|
484
|
+
print("="*80)
|
485
|
+
|
486
|
+
# Basic counts
|
487
|
+
print(f"\nTotal sessions in database: {stats['total_sessions']}")
|
488
|
+
print(f"Sessions after filtering: {stats['filtered_sessions']}")
|
489
|
+
print(f"Training examples generated: {stats['total_examples']}")
|
490
|
+
|
491
|
+
filter_rate = (stats['filtered_sessions'] / stats['total_sessions'] * 100) if stats['total_sessions'] > 0 else 0
|
492
|
+
print(f"Filter pass rate: {filter_rate:.1f}%")
|
493
|
+
|
494
|
+
# Reward distribution
|
495
|
+
if stats['reward_distribution'] and any(not np.isnan(x) for x in stats['reward_distribution']):
|
496
|
+
valid_rewards = [x for x in stats['reward_distribution'] if not np.isnan(x)]
|
497
|
+
if valid_rewards:
|
498
|
+
print(create_histogram(
|
499
|
+
valid_rewards,
|
500
|
+
bins=20,
|
501
|
+
title="Reward Distribution",
|
502
|
+
x_label="Total Reward",
|
503
|
+
y_label="Count"
|
504
|
+
))
|
505
|
+
|
506
|
+
print(f"\nReward statistics:")
|
507
|
+
print(f" Min: {min(valid_rewards):.2f}")
|
508
|
+
print(f" Max: {max(valid_rewards):.2f}")
|
509
|
+
print(f" Mean: {np.mean(valid_rewards):.2f}")
|
510
|
+
print(f" Median: {np.median(valid_rewards):.2f}")
|
511
|
+
else:
|
512
|
+
print("\nNo valid reward data to display.")
|
513
|
+
|
514
|
+
# Token distribution
|
515
|
+
if stats['token_distribution'] and any(not np.isnan(x) for x in stats['token_distribution']):
|
516
|
+
valid_tokens = [x for x in stats['token_distribution'] if not np.isnan(x)]
|
517
|
+
if valid_tokens:
|
518
|
+
print(create_histogram(
|
519
|
+
valid_tokens,
|
520
|
+
bins=20,
|
521
|
+
title="Token Usage Distribution",
|
522
|
+
x_label="Total Tokens",
|
523
|
+
y_label="Count"
|
524
|
+
))
|
525
|
+
|
526
|
+
# Model distribution
|
527
|
+
if stats['model_distribution']:
|
528
|
+
models = list(stats['model_distribution'].keys())
|
529
|
+
counts = list(stats['model_distribution'].values())
|
530
|
+
print(create_bar_chart(
|
531
|
+
models,
|
532
|
+
counts,
|
533
|
+
title="Model Usage",
|
534
|
+
show_values=True
|
535
|
+
))
|
536
|
+
|
537
|
+
print("\n" + "="*80)
|
538
|
+
|
539
|
+
|
540
|
+
def main():
|
541
|
+
parser = argparse.ArgumentParser(
|
542
|
+
description="Filter traces from Turso/SQLite v3 for Modal/Synth fine-tuning",
|
543
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
544
|
+
epilog="""
|
545
|
+
Example usage:
|
546
|
+
# Use default config
|
547
|
+
python filter_traces_sft_turso.py -d sqlite:///traces.db -o ft_data/training.jsonl
|
548
|
+
|
549
|
+
# Use custom config file
|
550
|
+
python filter_traces_sft_turso.py -d sqlite:///traces.db -c filter_config.toml
|
551
|
+
|
552
|
+
# Override config parameters
|
553
|
+
python filter_traces_sft_turso.py -d sqlite:///traces.db --min-reward 5.0 --max-cost 0.1
|
554
|
+
|
555
|
+
# Filter by model
|
556
|
+
python filter_traces_sft_turso.py -d sqlite:///traces.db --models "Qwen/Qwen2.5-7B-Instruct"
|
557
|
+
"""
|
558
|
+
)
|
559
|
+
|
560
|
+
parser.add_argument('-d', '--database', required=True, help='Path to Turso/SQLite database or connection URL')
|
561
|
+
parser.add_argument('-o', '--output', default='ft_data/training_modal.jsonl', help='Output JSONL file')
|
562
|
+
parser.add_argument('-c', '--config', help='Configuration TOML file')
|
563
|
+
|
564
|
+
# Filter overrides
|
565
|
+
parser.add_argument('--mode', choices=['trajectory', 'window'], help='Filtering mode')
|
566
|
+
parser.add_argument('--min-reward', type=float, help='Minimum total reward')
|
567
|
+
parser.add_argument('--min-achievements', type=int, help='Minimum achievements')
|
568
|
+
parser.add_argument('--max-cost', type=float, help='Maximum cost')
|
569
|
+
parser.add_argument('--max-tokens', type=int, help='Maximum tokens')
|
570
|
+
parser.add_argument('--models', nargs='+', help='Filter by model names (e.g., Qwen/Qwen2.5-7B-Instruct)')
|
571
|
+
|
572
|
+
parser.add_argument('--dry-run', action='store_true', help='Show statistics without writing output')
|
573
|
+
|
574
|
+
args = parser.parse_args()
|
575
|
+
|
576
|
+
# Load config
|
577
|
+
config = {
|
578
|
+
"mode": "trajectory",
|
579
|
+
"filters": {
|
580
|
+
"min_total_reward": 1.0,
|
581
|
+
"min_achievements": 0,
|
582
|
+
"max_cost": 10.0,
|
583
|
+
"max_tokens": 100000,
|
584
|
+
"models": [] # Empty means all models
|
585
|
+
}
|
586
|
+
}
|
587
|
+
|
588
|
+
if args.config:
|
589
|
+
with open(args.config, 'r') as f:
|
590
|
+
loaded_config = toml.load(f)
|
591
|
+
config.update(loaded_config)
|
592
|
+
|
593
|
+
# Apply command-line overrides
|
594
|
+
if args.mode:
|
595
|
+
config["mode"] = args.mode
|
596
|
+
if args.min_reward is not None:
|
597
|
+
config["filters"]["min_total_reward"] = args.min_reward
|
598
|
+
if args.min_achievements is not None:
|
599
|
+
config["filters"]["min_achievements"] = args.min_achievements
|
600
|
+
if args.max_cost is not None:
|
601
|
+
config["filters"]["max_cost"] = args.max_cost
|
602
|
+
if args.max_tokens is not None:
|
603
|
+
config["filters"]["max_tokens"] = args.max_tokens
|
604
|
+
if args.models:
|
605
|
+
config["filters"]["models"] = args.models
|
606
|
+
|
607
|
+
# Convert database path to proper URL format if needed
|
608
|
+
db_url = args.database
|
609
|
+
if db_url.startswith("sqlite:///"):
|
610
|
+
# Already in URL format
|
611
|
+
pass
|
612
|
+
elif db_url.endswith(".db"):
|
613
|
+
# Convert file path to URL
|
614
|
+
db_url = f"sqlite+aiosqlite:///{db_url}"
|
615
|
+
|
616
|
+
print(f"🤖 Modal/Synth Fine-Tuning Data Filter (v3)")
|
617
|
+
print(f"Using database: {db_url}")
|
618
|
+
print(f"Output file: {args.output}")
|
619
|
+
print(f"Mode: {config['mode']}")
|
620
|
+
print(f"Filters: {json.dumps(config['filters'], indent=2)}")
|
621
|
+
|
622
|
+
if args.dry_run:
|
623
|
+
print("\n🔍 DRY RUN - No output will be written")
|
624
|
+
|
625
|
+
# Run filtering
|
626
|
+
async def run():
|
627
|
+
num_examples, stats = await filter_traces_from_turso(
|
628
|
+
db_url,
|
629
|
+
args.output if not args.dry_run else "/dev/null",
|
630
|
+
config
|
631
|
+
)
|
632
|
+
|
633
|
+
# Print statistics
|
634
|
+
print_statistics(stats)
|
635
|
+
|
636
|
+
if not args.dry_run:
|
637
|
+
print(f"\n✅ Successfully wrote {num_examples} training examples to {args.output}")
|
638
|
+
print(f" Ready for Modal/Synth fine-tuning!")
|
639
|
+
else:
|
640
|
+
print(f"\n✅ Would write {num_examples} training examples (dry run)")
|
641
|
+
|
642
|
+
asyncio.run(run())
|
643
|
+
|
644
|
+
|
645
|
+
if __name__ == "__main__":
|
646
|
+
main()
|
synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/kick_off_ft_synth.py
ADDED
@@ -0,0 +1,34 @@
|
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
"""Kick off Synth fine-tuning runs using the same production backend
|
3
|
+
configuration that our integration tests rely on.
|
4
|
+
|
5
|
+
This script doesn't launch the actual fine-tuning process (that lives on the
|
6
|
+
backend service) – it simply ensures that the current environment is
|
7
|
+
correctly configured to talk to the production API so that any subsequent CLI
|
8
|
+
commands or library calls inherit the right base URL and API key.
|
9
|
+
|
10
|
+
It re-uses the `setup_synth_environment` helper from
|
11
|
+
`test_crafter_react_agent_lm_synth.py` to resolve the correct endpoint and
|
12
|
+
authentication details.
|
13
|
+
"""
|
14
|
+
|
15
|
+
# Re-use the helper we already maintain in the neighbouring test module.
|
16
|
+
from test_crafter_react_agent_lm_synth import setup_synth_environment # type: ignore
|
17
|
+
|
18
|
+
|
19
|
+
def main() -> None:
|
20
|
+
base_url, api_key = setup_synth_environment()
|
21
|
+
|
22
|
+
# Print info so that callers know what endpoint they are using.
|
23
|
+
print("✅ Synth/Modal backend configured")
|
24
|
+
print(f" BASE_URL: {base_url}")
|
25
|
+
print(" API_KEY: [hidden]")
|
26
|
+
|
27
|
+
# Optionally, you could kick off a fine-tune job here. For now we simply
|
28
|
+
# confirm that the environment variables are set so that users can run
|
29
|
+
# whatever downstream command they need (e.g. `uv run python some_ft.py`).
|
30
|
+
|
31
|
+
|
32
|
+
if __name__ == "__main__":
|
33
|
+
main()
|
34
|
+
|