ForgeCAD / agent_core /tools /build123d_tool.py
KaiWu
Cursor
feat(agent): replace Lux3D with image input for CAD
2d40989
Raw History Blame Contribute Delete
13.4 kB
import json
import shutil
import subprocess
import sys
import textwrap
from pathlib import Path
from agent_core.config import DEFAULT_BUILD123D_OUTPUT_PATH, WORKDIR
from agent_core.outputs import resolve_run_output, update_latest_link, workspace_relative, write_manifest
from agent_core.utils import json_response
BUILD123D_RUNNER = r"""
import contextlib
import io
import json
import sys
import traceback
from pathlib import Path
stdout_buffer = io.StringIO()
stderr_buffer = io.StringIO()
def tail(text, limit=4000):
if not text:
return ""
return text[-limit:]
def fail(stage, exc=None, error_type=None, error=None):
payload = {
"ok": False,
"stage": stage,
"error_type": error_type or (type(exc).__name__ if exc else "Error"),
"error": error or (str(exc) if exc else ""),
"traceback_tail": tail(traceback.format_exc() if exc else ""),
"stdout": tail(stdout_buffer.getvalue()),
"stderr": tail(stderr_buffer.getvalue()),
}
print(json.dumps(payload, ensure_ascii=False))
def unwrap_result(value):
for attr in ("part", "sketch", "line"):
try:
unwrapped = getattr(value, attr)
except Exception:
continue
if unwrapped is not None:
return unwrapped
return value
try:
request = json.loads(sys.stdin.read())
code = request["code"]
preview_path = Path(request["preview_path"])
step_path = Path(request["step_path"]) if request.get("step_path") else None
except Exception as exc:
fail("input", exc)
sys.exit(0)
try:
import build123d as bd
from build123d import * # noqa: F403
except Exception as exc:
fail("import", exc)
sys.exit(0)
try:
compiled = compile(code, "<build123d_code>", "exec")
except Exception as exc:
fail("syntax", exc)
sys.exit(0)
namespace = {
"__name__": "__build123d_user_code__",
"bd": bd,
}
namespace.update({name: getattr(bd, name) for name in dir(bd) if not name.startswith("_")})
try:
with contextlib.redirect_stdout(stdout_buffer), contextlib.redirect_stderr(stderr_buffer):
exec(compiled, namespace)
except Exception as exc:
fail("execution", exc)
sys.exit(0)
if "result" not in namespace:
fail("result", error_type="MissingResult", error="build123d code must assign the final model to variable 'result'.")
sys.exit(0)
result = namespace["result"]
if result is None:
fail("result", error_type="InvalidResult", error="'result' is None.")
sys.exit(0)
try:
exportable = unwrap_result(result)
size = exportable.bounding_box().size
bbox_mm = {"x": float(size.X), "y": float(size.Y), "z": float(size.Z)}
except Exception as exc:
fail("result", exc)
sys.exit(0)
try:
if step_path:
step_path.parent.mkdir(parents=True, exist_ok=True)
export_step(exportable, step_path) # noqa: F405
preview_path.parent.mkdir(parents=True, exist_ok=True)
export_stl(exportable, preview_path) # noqa: F405
except Exception as exc:
fail("export", exc)
sys.exit(0)
payload = {
"ok": True,
"stage": "done",
"step_path": str(step_path) if step_path else None,
"preview_path": str(preview_path),
"bbox_mm": bbox_mm,
"stdout": tail(stdout_buffer.getvalue()),
"stderr": tail(stderr_buffer.getvalue()),
}
print(json.dumps(payload, ensure_ascii=False))
"""
def _input_error(error_type: str, error: str) -> dict:
return {
"ok": False,
"stage": "input",
"error_type": error_type,
"error": error,
"traceback_tail": "",
"stdout": "",
"stderr": "",
}
def run_build123d(code: str, preview_path: Path, step_path: Path | None = None) -> dict:
"""Execute build123d code in a subprocess; always export an STL, export STEP only when step_path is given."""
if not code or not code.strip():
return _input_error("EmptyCode", "execute_build123d requires non-empty build123d code.")
request = {
"code": code,
"preview_path": str(preview_path),
"step_path": str(step_path) if step_path else None,
}
try:
process = subprocess.run(
[sys.executable, "-c", BUILD123D_RUNNER],
input=json.dumps(request, ensure_ascii=False),
cwd=WORKDIR,
capture_output=True,
text=True,
timeout=120,
)
except subprocess.TimeoutExpired as exc:
return {
"ok": False,
"stage": "execution",
"error_type": "TimeoutExpired",
"error": "build123d execution timed out after 120 seconds.",
"traceback_tail": "",
"stdout": exc.stdout[-4000:] if exc.stdout else "",
"stderr": exc.stderr[-4000:] if exc.stderr else "",
}
except Exception as exc:
return {
"ok": False,
"stage": "subprocess",
"error_type": type(exc).__name__,
"error": str(exc),
"traceback_tail": "",
"stdout": "",
"stderr": "",
}
raw_output = process.stdout.strip()
if not raw_output:
return {
"ok": False,
"stage": "subprocess",
"error_type": "NoRunnerOutput",
"error": "build123d runner returned no JSON output.",
"traceback_tail": "",
"stdout": "",
"stderr": process.stderr[-4000:],
}
try:
payload = json.loads(raw_output.splitlines()[-1])
except Exception as exc:
return {
"ok": False,
"stage": "subprocess",
"error_type": type(exc).__name__,
"error": f"Failed to parse build123d runner output: {exc}",
"traceback_tail": "",
"stdout": raw_output[-4000:],
"stderr": process.stderr[-4000:],
}
if process.returncode != 0 and payload.get("ok") is not False:
payload = {
"ok": False,
"stage": "subprocess",
"error_type": "RunnerFailed",
"error": f"build123d runner exited with code {process.returncode}.",
"traceback_tail": "",
"stdout": raw_output[-4000:],
"stderr": process.stderr[-4000:],
}
return payload
def publish_build123d_run(
code: str,
run_dir: Path,
run_id: str,
output: Path,
requested_output_path: str,
prompt: str | None = None,
verification: dict | None = None,
views_path: Path | None = None,
stdout: str = "",
stderr: str = "",
) -> dict:
"""Record an already executed run: manifest, verification, rendered views, and the latest link. Does not run the code."""
if verification is not None and views_path and Path(views_path).exists():
dest = run_dir / "views.png"
if Path(views_path).resolve() != dest.resolve():
shutil.copy2(views_path, dest)
verification = {**verification, "views_path": workspace_relative(dest)}
if verification is not None:
(run_dir / "verification.json").write_text(
json.dumps(verification, ensure_ascii=False, indent=2), encoding="utf-8"
)
payload = {
"ok": True,
"preview_path": str(run_dir / "preview.stl"),
"stdout": stdout,
"stderr": stderr,
}
manifest_path = write_manifest(
run_dir=run_dir,
run_id=run_id,
requested_output_path=requested_output_path,
output_path=output,
code=code,
prompt=prompt,
payload=payload,
generator="build123d",
verification=verification,
)
output_root = run_dir.parent.parent
latest_warning = update_latest_link(output_root, run_dir)
result = {
"ok": True,
"run_id": run_id,
"run_dir": workspace_relative(run_dir),
"output_path": workspace_relative(output),
"preview_path": workspace_relative(run_dir / "preview.stl"),
"manifest_path": workspace_relative(manifest_path),
"latest_path": workspace_relative(output_root / "latest"),
}
if latest_warning:
result["warning"] = latest_warning
return result
def save_build123d_run(
code: str,
output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
prompt: str | None = None,
verification: dict | None = None,
views_path: Path | None = None,
) -> dict:
"""Execute code once into a new run directory with STEP + STL + manifest (+ verification and views if given)."""
try:
run_dir, output, run_id = resolve_run_output(output_path)
except Exception as exc:
return _input_error(type(exc).__name__, str(exc))
payload = run_build123d(code, run_dir / "preview.stl", output)
if not payload.get("ok"):
return payload
if verification is not None:
if views_path:
shutil.copy2(views_path, run_dir / "views.png")
verification = {**verification, "views_path": workspace_relative(run_dir / "views.png")}
(run_dir / "verification.json").write_text(
json.dumps(verification, ensure_ascii=False, indent=2), encoding="utf-8"
)
payload.pop("step_path", None)
manifest_path = write_manifest(
run_dir=run_dir,
run_id=run_id,
requested_output_path=output_path,
output_path=output,
code=code,
prompt=prompt,
payload=payload,
generator="build123d",
verification=verification,
)
output_root = run_dir.parent.parent
latest_warning = update_latest_link(output_root, run_dir)
payload["run_id"] = run_id
payload["run_dir"] = workspace_relative(run_dir)
payload["output_path"] = workspace_relative(output)
payload["preview_path"] = workspace_relative(Path(payload["preview_path"]))
payload["manifest_path"] = workspace_relative(manifest_path)
payload["latest_path"] = workspace_relative(output_root / "latest")
if latest_warning:
payload["warning"] = latest_warning
return payload
def run_execute_build123d(
code: str,
output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
prompt: str | None = None,
) -> str:
return json_response(save_build123d_run(code, output_path, prompt))
TOOL_SCHEMA = {
"name": "execute_build123d",
"description": textwrap.dedent("""
Execute build123d Python code, verify the model from rendered views, and save it as STEP + STL once accepted.
The code must assign the final build123d model to a variable named result.
build123d public symbols are pre-imported, and build123d is also available as bd.
A model is saved only when the result contains output_path; candidates that fail verification are not saved.
Do NOT supply output_path in normal usage. The tool automatically writes files to the configured artifact directory under a unique run directory. Only set output_path if the user explicitly requests a different location.
""").strip(),
"input_schema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "build123d Python code. It must assign the final model to variable 'result'.",
},
"output_path": {
"type": "string",
"description": "Advanced: custom STEP file path or output directory. Omit this field to use the configured artifact directory (recommended).",
},
},
"required": ["code"],
},
}
PROMPT_SECTION = """
For precise CAD tasks:
- Use execute_build123d for dimensioned parts, parametric geometry, engineering models, and STEP/CAD output.
- Write build123d Python code.
- The code must assign the final model to a variable named result.
- build123d public symbols are pre-imported, and build123d is also available as bd.
- BuildPart, BuildSketch, and BuildLine builder objects are accepted; the tool will unwrap their .part, .sketch, or .line result.
- Call execute_build123d with just the code; do NOT pass output_path. The tool writes outputs into the configured artifact directory under a unique run directory automatically.
- If execute_build123d returns ok=false, inspect the structured error, fix the code, and call execute_build123d again.
- When ok=true, the result may include a verification object produced by an independent reviewer from rendered views. Follow verification.instruction. If it failed, fix the failed checklist items and hard_checks problems by editing your previous code rather than starting over.
- The model is saved only when the result contains output_path. Without output_path nothing was saved yet, so do not report any file path.
- CadQuery is not enabled in the current runtime. If the user explicitly asks for CadQuery, say that the active CAD tool is build123d.
- When the user message includes an image, use the image for shape and structure. If text and image conflict, follow the text for dimensions and the image for shape. If a dimension is unclear, estimate it and state the estimate in the reply.
- If the text already specifies what to build, build that even when the image is blurry.
- If the image is blank, unrelated, or unrecognizable, or the shape and structure cannot be determined, and the text does not specify an object, do not call execute_build123d.
""".strip()