179 lines
7.8 KiB
Python
179 lines
7.8 KiB
Python
"""支撑理解层"多轮agent循环"的有状态建模会话。
|
|
|
|
跟executor.run_ir()的批处理模式不同:这里每次只执行一步操作,立刻把结果
|
|
(成功/失败、最新状态)反馈回去,给理解层的模型一个可以"边做边看、自己发现
|
|
问题自己改"的循环,而不是盲目吐出一整份JSON、事后才能核对——这是参考同类
|
|
项目"编码agent驱动CAD、边做边看"的思路,内建进我们自己的后端,不需要用户
|
|
额外装一个编码agent。
|
|
"""
|
|
|
|
from pathlib import Path
|
|
|
|
from .claims import check_claims
|
|
from .postcondition import PostconditionError, check_postcondition
|
|
from .executor import validate_params
|
|
from .validation import solid_errors
|
|
|
|
|
|
class AgentSession:
|
|
def __init__(self, registry: dict):
|
|
self.registry = registry
|
|
self.context = {}
|
|
self.trace = []
|
|
self._next_id = 0
|
|
|
|
def _auto_id(self) -> str:
|
|
self._next_id += 1
|
|
while f"op{self._next_id}" in self.context:
|
|
self._next_id += 1
|
|
return f"op{self._next_id}"
|
|
|
|
def apply_op(self, op_name: str, params: dict, target: str | None = None, op_id: str | None = None) -> dict:
|
|
if op_name not in self.registry:
|
|
return {"ok": False, "error": f"UNKNOWN_CAPABILITY: 能力库中不存在 '{op_name}'"}
|
|
|
|
cap = self.registry[op_name]
|
|
errors = validate_params(cap.contract, params)
|
|
if errors:
|
|
return {"ok": False, "error": "; ".join(errors)}
|
|
if op_id is not None and (not isinstance(op_id, str) or not op_id or op_id in self.context):
|
|
return {"ok": False, "error": "INVALID_ID: id 必须非空且不可重复;修复请使用新 id 或 rebuild_model"}
|
|
if target is not None and not isinstance(target, str):
|
|
return {"ok": False, "error": "INVALID_TARGET: target 必须是字符串或 null"}
|
|
|
|
if target == "":
|
|
target = None
|
|
target_obj = None
|
|
if target:
|
|
if target not in self.context:
|
|
return {
|
|
"ok": False,
|
|
"error": f"UNKNOWN_ID: 引用的id '{target}' 不存在,当前已有的id: {list(self.context)}",
|
|
}
|
|
target_obj = self.context[target]
|
|
|
|
if hasattr(cap.impl, "validate"):
|
|
try:
|
|
errors += cap.impl.validate(self.context, target_obj, params) or []
|
|
except Exception as exc:
|
|
errors.append(f"VALIDATION_ERROR: {exc}")
|
|
|
|
if errors:
|
|
return {"ok": False, "error": "; ".join(errors)}
|
|
|
|
try:
|
|
result = cap.impl.run(self.context, target_obj, params)
|
|
except Exception as e: # noqa: BLE001 - 统一包装成结构化错误反馈给理解层的agent
|
|
return {"ok": False, "error": f"EXECUTION_ERROR: {e}"}
|
|
|
|
# 每一步都无条件核对契约声明的postcondition——不通过就当场打回给agent,
|
|
# 不写进context,防止一个"其实什么都没干"的操作被后续步骤当成成功结果继续用
|
|
try:
|
|
check_postcondition(
|
|
op_name, cap.contract.get("postcondition_check"), target_obj, result
|
|
)
|
|
except PostconditionError as e:
|
|
return {"ok": False, "error": str(e)}
|
|
|
|
summary = self._summarize(result)
|
|
if summary.get("is_valid") is False:
|
|
return {"ok": False, "error": "INVALID_GEOMETRY: 操作产生无效几何,未写入建模上下文;请修正当前操作"}
|
|
final_id = op_id or self._auto_id()
|
|
self.context[final_id] = result
|
|
self.trace.append({"op": op_name, "id": final_id, "target": target, "params": params})
|
|
return {"ok": True, "id": final_id, **summary}
|
|
|
|
def _summarize(self, shape) -> dict:
|
|
try:
|
|
bbox = shape.bounding_box()
|
|
return {
|
|
"solids": len(shape.solids()),
|
|
**({"sketch_face_normals": [list(f.normal_at()) for f in shape.faces()[:8]]} if not shape.solids() else {}),
|
|
**({"solid_components": [{"bbox_min": list(s.bounding_box().min), "bbox_max": list(s.bounding_box().max)} for s in shape.solids()[:32]]} if len(shape.solids()) > 1 else {}),
|
|
"volume_mm3": round(shape.volume, 2),
|
|
"bbox_min": [round(bbox.min.X, 2), round(bbox.min.Y, 2), round(bbox.min.Z, 2)],
|
|
"bbox_max": [round(bbox.max.X, 2), round(bbox.max.Y, 2), round(bbox.max.Z, 2)],
|
|
"is_valid": bool(shape.is_valid),
|
|
}
|
|
except Exception as e: # noqa: BLE001
|
|
return {"summary_error": str(e)}
|
|
|
|
def get_state(self) -> dict:
|
|
return {
|
|
"existing_ids": list(self.context.keys()),
|
|
"op_count": len(self.trace),
|
|
"last_op": self.trace[-1] if self.trace else None,
|
|
}
|
|
|
|
def describe(self, op_id: str) -> dict:
|
|
if op_id not in self.context:
|
|
return {"ok": False, "error": f"UNKNOWN_ID: '{op_id}' 不存在,当前已有的id: {list(self.context)}"}
|
|
return {"ok": True, **self._summarize(self.context[op_id])}
|
|
|
|
def render_png(self, op_id: str, view: str = "iso") -> bytes | None:
|
|
if op_id not in self.context:
|
|
return None
|
|
from .render import render_shape_png
|
|
|
|
return render_shape_png(self.context[op_id], view=view)
|
|
|
|
def finish(self, output_id: str, claims: list, expected_solid_count=None, out_dir: Path = None) -> dict:
|
|
if output_id not in self.context:
|
|
return {"ok": False, "error": f"UNKNOWN_ID: output_id '{output_id}' 不存在,当前已有的id: {list(self.context)}"}
|
|
final = self.context[output_id]
|
|
errors = solid_errors(final, expected_solid_count)
|
|
if errors:
|
|
return {"ok": False, "error": "; ".join(errors)}
|
|
|
|
if not final.is_valid:
|
|
return {"ok": False, "error": "INVALID_GEOMETRY: 最终实体几何无效(is_valid=False),检查布尔运算是否产生了非法结果"}
|
|
invalid_solids = [s for s in final.solids() if not s.is_valid]
|
|
if invalid_solids:
|
|
return {"ok": False, "error": f"INVALID_SOLID: 最终结果里有{len(invalid_solids)}个实体几何无效"}
|
|
|
|
if isinstance(expected_solid_count, str):
|
|
try:
|
|
expected_solid_count = int(expected_solid_count)
|
|
except ValueError:
|
|
expected_solid_count = None
|
|
if expected_solid_count is not None:
|
|
actual = len(final.solids())
|
|
if actual != expected_solid_count:
|
|
return {
|
|
"ok": False,
|
|
"error": f"SOLID_COUNT_MISMATCH: 声明预期{expected_solid_count}个独立实体,实际生成了{actual}个",
|
|
}
|
|
|
|
if claims:
|
|
violations = check_claims(claims, self.context, self.trace)
|
|
if violations:
|
|
return {"ok": False, "error": "; ".join(violations)}
|
|
|
|
from .cad_export import export_verified
|
|
|
|
out_dir = Path(out_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
step_path = out_dir / "model.step"
|
|
stl_path = out_dir / "model.stl"
|
|
try:
|
|
export_check = export_verified(final, step_path, stl_path)
|
|
except ValueError as exc:
|
|
return {"ok": False, "error": str(exc)}
|
|
|
|
bbox = final.bounding_box()
|
|
return {
|
|
"ok": True,
|
|
"output_id": output_id,
|
|
"export_validation": export_check,
|
|
"operations": self.trace,
|
|
"volume_mm3": final.volume,
|
|
"bounding_box_mm": {
|
|
"min": [bbox.min.X, bbox.min.Y, bbox.min.Z],
|
|
"max": [bbox.max.X, bbox.max.Y, bbox.max.Z],
|
|
},
|
|
"step_file": str(step_path),
|
|
"stl_file": str(stl_path),
|
|
"expected_solid_count": expected_solid_count,
|
|
"claims": claims,
|
|
}
|