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 | @ray.remote(num_cpus=1, max_concurrency=1)
class Runner:
def __init__(
self,
*,
env_cfg: DictConfig,
agent_cfg: DictConfig,
inference_mngr,
tracing_level: str = "off",
):
self.agent: Agent = hydra.utils.instantiate(agent_cfg, inference_mngr=inference_mngr)
self.env: Environment = hydra.utils.instantiate(env_cfg)
# Initialize observability tracer
try:
worker_id = ray.get_runtime_context().get_actor_id() or "runner_unknown"
except Exception:
worker_id = f"runner_{uuid.uuid4().hex[:8]}"
level = obs.TracingLevel(tracing_level) if tracing_level else obs.TracingLevel.FULL
self.tracer = obs.Tracer(
worker_id=worker_id,
worker_type="runner",
level=level,
collector=obs.get_protobuf_collector(),
)
# Share tracer with agent for flow tracing (agent→inference_manager)
self.agent.tracer = self.tracer
@staticmethod
async def _maybe_await(value):
if inspect.isawaitable(value):
return await value
return value
async def _play_timestep(
self,
observation: Chat,
timestep_idx: int = 0,
) -> tuple[TimeStep, Chat, bool]:
"""Helper function that progresses the agent and environment by one timestep"""
# Agent returns a list of chats (as lists of dicts) and an action (dict)
with self.tracer.span("get_tool_schemas", category="inference"):
available_tool_schemas = await self._maybe_await(self.env.get_tool_schemas())
# Agent.act() is already traced via @traced_method decorator - no wrapper needed
chats, action = await self.agent.act(observation, available_tool_schemas)
tool_calls = action.tool_calls or []
# Environment steps with the action, returns new observation, reward, done
logger.debug(
"Act: " + "\n".join([f"{tc.function.get('name')}: {tc.function.get('arguments')}" for tc in tool_calls])
)
with self.tracer.span("env.step", category="inference", timestep_idx=timestep_idx) as step_span:
new_observation, reward, done = await self._maybe_await(self.env.step(action))
step_span.set_attribute("reward", reward)
step_span.set_attribute("done", done)
# The timestep we will train on:
ts = TimeStep(
chats=chats,
reward=reward,
done=done,
available_tool_schemas=available_tool_schemas,
)
return ts, new_observation, done
async def play_episode(self, reset_kwargs: dict) -> Trajectory: # noqa: PLR0915
timesteps = []
error_info = None
# Generate trace ID for this episode
trace_id = str(uuid.uuid4())
task = reset_kwargs.get("task")
task_id = getattr(task, "task_id", "unknown") if task else "unknown"
# Use task_unique_id for flow matching (passed from orchestrator)
task_unique_id = reset_kwargs.get("task_unique_id", id(task) if task else 0)
with self.tracer.span(
"episode",
category="episode",
trace_id=trace_id,
task_id=task_id,
semantic="play_single_episode_with_environment",
) as episode_span:
# Flow end: task received by runner (matches flow_start in orchestrator)
episode_span.end_flow(obs.create_flow_id("task", str(task_unique_id)))
# Attempt environment reset, capture and return a safe Trajectory on failure
try:
with self.tracer.span("env.reset", category="inference"):
observation = await self._maybe_await(self.env.reset(**reset_kwargs))
except Exception as e:
logger.error("Episode failed during reset", exc_info=True)
error_info = obs.create_error_info(e)
if hasattr(self.env, "cleanup"):
try:
await self.env.cleanup()
except Exception:
logger.exception("Environment cleanup failed.")
logger.info(f"Episode completed: {len(timesteps)} timesteps, error={error_info is not None}")
episode_span.set_attribute("error", True)
episode_span.set_attribute("num_timesteps", 0)
return Trajectory(timesteps=timesteps, reset_kwargs=reset_kwargs, error_info=error_info)
with self.tracer.span("agent.init_after_reset", category="inference"):
await self._maybe_await(self.agent.init_after_reset())
done = False
timestep_idx = 0
try:
while not done:
with self.tracer.span("timestep", category="inference", timestep_idx=timestep_idx):
ts, observation, done = await self._play_timestep(observation, timestep_idx)
timesteps.append(ts)
timestep_idx += 1
except Exception as e:
logger.error("Episode terminated due to error", exc_info=True)
error_info = obs.create_error_info(e)
if hasattr(self.env, "cleanup"):
try:
await self.env.cleanup()
except Exception:
logger.exception("Environment cleanup failed.")
episode_span.set_attribute("num_timesteps", len(timesteps))
episode_span.set_attribute("error", error_info is not None)
if timesteps and timesteps[-1].reward is not None:
episode_span.set_attribute("final_reward", timesteps[-1].reward)
# Flow start: episode returning to orchestrator
# This creates visual connection: episode → orchestrator.traj_out
episode_span.start_flow(obs.create_flow_id("episode_return", str(task_unique_id)))
logger.info(f"Episode completed: {len(timesteps)} timesteps, error={error_info is not None}")
episode_id = self.env.get_episode_id()
# Get last response flow ID from agent for tracing termination at traj_out
trace_last_response_flow_id = getattr(self.agent, "_trace_last_response_flow_id", None)
if type(self.env).__name__ == "AREEnvironment":
try:
evaluation_details = await self._maybe_await(self.env.get_evaluation_details())
if evaluation_details is not None:
logger.debug("Returning AREEvaluatedTrajectory with evaluation details")
return AREEvaluatedTrajectory(
timesteps=timesteps,
reset_kwargs=reset_kwargs,
error_info=error_info,
are_evaluation=evaluation_details,
episode_id=episode_id,
trace_last_response_flow_id=trace_last_response_flow_id,
)
except Exception:
logger.exception("Failed to get evaluation details")
return Trajectory(
timesteps=timesteps,
reset_kwargs=reset_kwargs,
error_info=error_info,
episode_id=episode_id,
trace_last_response_flow_id=trace_last_response_flow_id,
)
|