import logging import json import os import pybullet as pb from llm_panda import config logger = logging.getLogger(__name__) class ExecutionMonitor: def __init__(self, scene, controller, agent): self.scene = scene self.controller = controller self.agent = agent def verify_step(self, step, held_before, expected_location, carried_object, pending_target_pos): func = step.get("function") args = step.get("args", {}) if func != "pick_up" and self.controller.is_stuck(): return False, f"IK joint stuck during '{func}'" if func == "pick_up": name = args.get("object_id") oid = self.scene.name_to_id(name) if oid is None: return False, f"unknown object '{name}'" if carried_object != oid: # Rule-based validation from gripper return False, f"pick_up('{name}') did not secure the object (gripper missed)" pos, _ = pb.getBasePositionAndOrientation(oid) if pos[2] < config.TABLE_TOP_Z + 0.05: return False, f"'{name}' was not lifted (z={pos[2]:.3f})" return True, "" if func == "move_to": if carried_object is None: return False, "move_to ended with nothing held" target = pending_target_pos if target is not None: tcp = self.controller.tcp_position() d = ((tcp[0] - target[0]) ** 2 + (tcp[1] - target[1]) ** 2) ** 0.5 if d > 0.12: return False, f"arm stopped {d:.3f} m short of the target XY (likely stuck)" return True, "" if func == "place_down": if held_before is None: return True, "" if carried_object is not None: return False, "gripper still holding after place_down" pos, _ = pb.getBasePositionAndOrientation(held_before) if pos[2] < config.TABLE_TOP_Z - 0.10: return False, f"placed object fell off the surface (z={pos[2]:.3f})" loc = self.scene.classify_location(pos) expected_surface = "table" if expected_location == "buffer" else expected_location if expected_surface and loc != expected_surface: return False, f"object landed at '{loc}', expected '{expected_surface}'" return True, "" return True, "" def verify_goal(self, nl_command, scene_state_text, resolved_goal=None): """ Uses LLM (if available) or Rule-based to check if the goal is met. Since we might not want to incur an extra API call if not strictly necessary, we can delegate to the agent's check_goal method. """ enabled = os.environ.get( "STRUCTURED_GOAL_CHECK_ENABLED", "true" ).lower() not in {"0", "false", "no", "off"} if enabled and resolved_goal is not None: result = self._verify_predicates( resolved_goal, scene_state_text, scene=self.scene, ) if result is not None: return result nl_command = resolved_goal.canonical_instruction if hasattr(self.agent, "check_goal"): return self.agent.check_goal(nl_command, scene_state_text) return True, "Assumed Goal Reached (Agent lacks check_goal method)" @staticmethod def _verify_predicates(resolved_goal, scene_state_text, scene=None): """Evaluate common robot goals without another probabilistic LLM call.""" try: state = ( json.loads(scene_state_text) if isinstance(scene_state_text, str) else scene_state_text ) except (TypeError, ValueError, json.JSONDecodeError): return None if not isinstance(state, dict): return None objects = { obj.get("name"): obj for obj in state.get("objects", []) if isinstance(obj, dict) and obj.get("name") } failures = [] passed = [] for predicate in resolved_goal.predicates: if predicate.type == "carried_object_is": actual = state.get("carried_object") ok = actual == predicate.object_id detail = ( f"carried_object={actual!r}, expected {predicate.object_id!r}" ) elif predicate.type == "location_is": obj = objects.get(predicate.object_id, {}) actual = obj.get("location") expected = ( "table" if predicate.location_id == "buffer" else predicate.location_id ) ok = actual == expected detail = ( f"{predicate.object_id}.location={actual!r}, expected " f"{expected!r}" ) elif predicate.type == "position_near": obj = objects.get(predicate.object_id, {}) actual_position = obj.get("position") target_position = predicate.target_position tolerance = predicate.tolerance or 0.04 same_surface = ( not predicate.location_id or obj.get("location") == predicate.location_id ) if ( isinstance(actual_position, (list, tuple)) and len(actual_position) >= 2 and target_position and len(target_position) >= 2 ): distance = ( (actual_position[0] - target_position[0]) ** 2 + (actual_position[1] - target_position[1]) ** 2 ) ** 0.5 ok = distance <= tolerance and same_surface else: distance = None ok = False detail = ( f"{predicate.object_id}.position={actual_position!r}, " f"expected near {target_position!r} " f"(tolerance={tolerance:.3f}, distance={distance!r})" ) elif predicate.type == "relation_is": obj = objects.get(predicate.object_id, {}) relations = obj.get("relations", {}) or {} if predicate.relation == "next_to": actual = (obj.get("distances", {}) or {}).get( predicate.relative_to ) same_surface = ( obj.get("location") == objects.get(predicate.relative_to, {}).get("location") ) ok = ( isinstance(actual, (int, float)) and actual <= max(0.20, config.RELATION_TARGET_GAP * 1.5) and same_surface ) else: actual = relations.get(predicate.relation) if isinstance(actual, list): ok = predicate.relative_to in actual else: ok = actual == predicate.relative_to if ( not ok and predicate.relation == "on_top_of" and scene is not None and hasattr(scene, "is_on_top") ): ok = scene.is_on_top( predicate.object_id, predicate.relative_to, ) if ok: actual = "verified_from_live_aabb" detail = ( f"{predicate.object_id}.{predicate.relation}={actual!r}, " f"expected {predicate.relative_to!r}" ) else: return None (passed if ok else failures).append(detail) if failures: return False, "Structured goal failed: " + "; ".join(failures) return True, "Structured goal satisfied: " + "; ".join(passed)