BR的头像Blog
  • 首页
  • 关于
  • 博客
  • 日常
  • 相册
  • 音乐馆
  • 经历
  • 作品集
  • 归档
  • 学术档案

Powered by Next.js

© 2026 BR. All rights reserved.

返回作品集

Projects / ASSEMCAD

基于公理的复杂CAD装配体生成

PaperPythonAgent Harness
项目文件93 个文件92 个可预览文件
登录后发表 Issue

这里还没有讨论,欢迎提出问题与建议。

text2cad/README.md

text2cad — Text → 3D CAD Assembly

A standalone Python agent that turns natural-language descriptions of mechanical assemblies into 3D STEP files via a deterministic, axiom-grounded pipeline.

"A single-stage spur-gear reducer with bearing-supported shaft"
    ↓  python -m agent run "..."
    ↓  decompose → write-spec → run pipeline
    ↓
reducer.step  (3D geometry, ready for CAM/FEA)

The agent calls a configurable LLM (any OpenAI-compatible HTTP API works out of the box) for phases 1–2 and runs the deterministic 7-stage pipeline for phase 3. No external host required.

Highlights

  • Natural-language input — describe the assembly in plain English (or Chinese).
  • 13 parametric factories — plates, brackets, channels, bosses, flanges, housings, shafts, hubs, fasteners (bolt/nut/washer), gears, bearings.
  • Agent-authored custom parts (Phase 1) — when none of the built-ins fit (custom housings, brackets, connectors, covers...) the agent emits a user.* factory and the synth pre-stage has the LLM write a sandbox-validated CadQuery module on demand. Cached under user_factories/.
  • 7 mate types — face_to_face (with u/v/offset_normal for spreading parts across one face), coaxial, coaxial_face, gear_mesh, press_fit, thread_engage, snap_to_face.
  • 12 port types with a compatibility matrix that catches mating mistakes before geometry runs.
  • Geometry-aware verify (Phase 1.5) — pairwise clash detection (BRepAlgoAPI_Common), DOF graph reachability, deterministic offscreen render, and a per-part single-solid invariant.
  • Port-geometry consistency (Phase 1.5.6) — every port a factory advertises must reference real geometry on the as-built solid (cavity for bore-like, on-face for flat_face, material along axis for shaft-like). Catches phantom features (forgotten .cut(), Workplane("XZ").extrude sign trap, etc.) at synth time. The safe_union helper pairs with this to prevent silent disjoint-solid Compounds when combining sub-parts.
  • Axiom-grounded — every part/mate is justified by an entry in data/axioms_final.json.
  • Fail-fast pipeline — clear error messages, deterministic output, full provenance.

Quick Start

1. Conda env with CadQuery

bash
conda create -n cad python=3.10
conda activate cad
conda install -c conda-forge cadquery
pip install cq_warehouse cq_gears pyyaml jinja2 jsonschema

2. Install text2cad in editable mode

bash
# Assembly extension (CadQuery factories)
pip install -e cad-assembly-extension

# Agent + LLM client (httpx)
pip install -e ".[agent]"

3. Configure your LLM (config file only — no env vars)

Copy the template and fill in your values:

bash
cp config.yaml.example config.yaml
yaml
# <repo_root>/config.yaml — gitignored, edit freely
provider: openai_compat
base_url: https://api.deepseek.com/v1   # or any OpenAI-compatible endpoint:
                                        # vLLM / TGI / DeepSeek / Qwen /
                                        # Moonshot / Zhipu / Together / OpenAI / ...
api_key:  sk-...
model:    deepseek-chat
timeout_s: 120

You can also keep multiple provider blocks side-by-side and select with --provider:

yaml
provider: openai_compat       # default

openai_compat:
  base_url: https://api.deepseek.com/v1
  api_key:  sk-...
  model:    deepseek-chat

# Reserved for future providers (currently stubs):
# anthropic: { model: claude-sonnet-4-6, api_key: ... }
# ollama:    { base_url: http://localhost:11434/v1, model: qwen2.5-coder }

Pass --config /path/to/other.yaml to use a different config file.

4. Run

bash
# End-to-end
python -m agent run "A single-stage spur-gear reducer with bearing-supported shaft" \
    --build-root build/

# One phase at a time
python -m agent decompose "..." --out drafts/r.json
python -m agent write-spec drafts/r.json --specs-dir specs/
python -m agent generate specs/reducer.yaml --build-root build/

The agent must run inside the cad conda env so the pipeline can import CadQuery for stages 5–6:

bash
conda run -n cad python -m agent run "..."
# or directly:
"D:/conda/envs/cad/python.exe" -m agent run "..."

Repository Layout

text2cad/
├── agent/                            # Standalone agent (the entry point)
│   ├── cli.py                        # `python -m agent {run,decompose,write-spec,generate}`
│   ├── orchestrator.py               # 3-phase chaining
│   ├── decomposer.py                 # NL → AssemblyDraft (LLM call + repair loop)
│   ├── spec_writer.py                # AssemblyDraft → YAML, round-tripped through load_spec
│   ├── action_space.py               # renders Section A from factories.json
│   └── prompts/system.md             # system prompt — canonical pipeline reference
├── llm/                              # LLM client abstraction (also used by Phase 1)
│   ├── client.py                     # LLMClient Protocol
│   ├── config.py                     # YAML config loader (project-root config.yaml, no env vars)
│   ├── cache.py                      # SHA-256 disk cache
│   └── providers/                    # openai_compat (primary), anthropic/ollama/hf_local stubs, echo (tests)
├── llm_factory/                      # Phase 1 — agent-authored custom-part factory
│   ├── synthesizer.py                # NL + ports → validated CadQuery module
│   ├── sandbox.py                    # subprocess-isolated AST + build + bbox + port checks
│   ├── factory_contract.py           # required exports (PARAMS_SCHEMA / PORTS / build)
│   ├── registry.py                   # user_factories/registry.json reader/writer + merge
│   ├── cli.py                        # `python -m llm_factory {synth,list,show-merged}`
│   └── prompts/                      # system + factory_template + few-shot examples
├── user_factories/                   # cache of agent-authored modules (gitignored except registry.json)
├── cad_assembly/                     # Pipeline driver (deterministic backend)
│   └── pipeline/
│       ├── driver.py                 # orchestrator
│       ├── spec.py                   # YAML spec loader
│       ├── planner.py                # spec → tree.json (axiom resolution)
│       ├── assemble.py               # tree.json → STEP (in-process; replaces the old emit+execute pair)
│       ├── clash.py                  # pairwise interference (BRepAlgoAPI_Common)
│       ├── dofcheck.py               # graph BFS over mate edges
│       ├── render.py                 # offscreen PNG via matplotlib
│       ├── verify.py                 # STEP volume + bbox check + clash/dof merge
│       └── provenance.py             # axiom audit writer
├── cad-assembly-extension/           # CadQuery factory implementations (separate sub-project)
│   └── cad_assembly_ext/
│       ├── base_frame/               # plates, brackets, housings, shafts, ...
│       ├── adapters/                 # fasteners, gears, bearings (cq_warehouse / cq_gears)
│       ├── mate_types.py             # 7 mate transforms
│       ├── port.py                   # Port system + compatibility matrix + add_port(geometry_check=...)
│       ├── port_geometry.py          # bore / shaft / flat_face geometry-consistency checks (Phase 1.5.6.ter)
│       ├── workplane_ext.py          # Workplane extension methods + safe_union helper (Phase 1.5.6.bis)
│       ├── factory_dispatch.py       # node → cq.Workplane (in-process; replaces tree2code)
│       └── assemble_from_tree.py     # tree.json → AssemblyExt
├── schema/                           # JSON schema, factory registry, validator
├── data/axioms_final.json            # engineering axiom set v2.0.0
├── demos/                            # reference YAML specs + smoke_test.py
└── docs/                             # agent usage + phase design notes

Workflow

Phase 1 — decompose

Decomposes the description into parts (factory + params) and mates (assembly sequence). The LLM is asked for a strict JSON object that matches agent/schemas.py::AssemblyDraft.

Phase 2 — write-spec

Serializes the draft to a YAML spec at ./specs/<tree_id>.yaml, then re-parses it through cad_assembly.pipeline.spec.load_spec to confirm on-disk validity.

Phase 3 — run-pipeline

Runs the deterministic pipeline:

#StageOutput
1loadSpecDoc (in memory) + build/<id>/spec.yaml snapshot
1.5synthuser_factories/<name>.py (only when the spec uses user.*); also gates solid_count == 1, port-geometry consistency, and the AST allow-list
2plan<tree_id>.tree.json
3validate(raises on failure)
4assemble<tree_id>.step (in-process; no <tree_id>.py written)
5verify

Every stage is fail-fast — stage N never runs if stage N-1 raised.

Agent-authored custom parts (Phase 1)

When the user's description involves geometry no built-in factory can produce — custom housings, weird flanges, decorative covers, transition fittings, anything bespoke — the agent emits a part with factory: user.<short_name> plus two extra fields the built-ins don't need: description (NL geometry brief in mm) and expected_ports. The pipeline's synth pre-stage then asks the LLM to write a CadQuery factory module that satisfies the contract, sandboxes it (AST scan + subprocess build + bbox/port checks), and caches the result under user_factories/<short_name>.py. Re-running the same spec hits the content-addressed cache and skips the LLM entirely.

The agent decides on its own per-part whether to use a built-in or to synthesise a user.* — see Rule 5 + the "On-demand synthesis" section in agent/prompts/system.md. You don't configure anything extra: config.yaml drives both decompose and synth.

Runnable case

A NL → STEP run that exercises both built-in fasteners and an agent-authored housing:

bash
conda run -n cad python -m agent run \
    "A small open-front rectangular housing 40x30x25 mm with 3 mm walls. \
Two M4 clearance holes on the back wall, 28 mm apart, for mounting a small motor. \
Show one M4 bolt through the left hole with a nut on the inside." \
    --tree-id custom_motor_mount --build-root build/

Or run the hand-written equivalent spec to skip phase 1/2 and exercise just the deterministic backend + the synth pre-stage:

bash
conda run -n cad python -m cad_assembly.pipeline run \
    demos/custom_motor_mount.yaml --build-root build/

How the logs distinguish agent-handwritten parts

Every stage prefixes its output with a [stage_name] tag. The two new signals for Phase 1 are [decompose] (after the agent's NL→draft call) and [synth] (the pre-stage that runs before plan):

[decompose] decompose_0: tree_id=custom_motor_mount parts=3 (2 built-in, 1 agent-authored user.*) -- custom: housing=>user.simple_box_mount
[load] spec=specs/custom_motor_mount.yaml tree_id=custom_motor_mount
[synth] 1 agent-authored user.* part(s) detected: user.simple_box_mount
[synth] user.simple_box_mount: agent-authored, NEWLY SYNTHESIZED (0 repair round(s)) -> user_factories/simple_box_mount.py
[plan]  wrote build/custom_motor_mount/custom_motor_mount.tree.json
[validate] VALID: build/custom_motor_mount/custom_motor_mount.tree.json
[assemble] 3 part(s) -> custom_motor_mount.step (Validation passed: no issues found.)
[verify] no clash among 3 parts (3 pairs checked)
[verify] DOF: all 3 parts connected to base 'housing'
[verify] render: 3 part(s) -> custom_motor_mount.png
[verify] custom_motor_mount.step volume=27451.000 bbox=(40.0, 30.0, 41.0)
[provenance] wrote build/custom_motor_mount/provenance.json

On a second run, the synth line becomes agent-authored, cache hit (skipped LLM) — the same content-addressed cache key skips the LLM round-trip entirely.

The final agent summary at the end of python -m agent run also lists the custom parts:

OK: custom_motor_mount
  parts:   3 total — 2 built-in + 1 agent-authored user.*
    custom: housing -> user.simple_box_mount
  spec:    specs/custom_motor_mount.yaml
  tree:    build/custom_motor_mount/custom_motor_mount.tree.json
  step:    build/custom_motor_mount/custom_motor_mount.step
  png:     build/custom_motor_mount/custom_motor_mount.png
  verify:  build/custom_motor_mount/verify.json
  clash:   build/custom_motor_mount/clash.json
  dof:     build/custom_motor_mount/dof.json
  provenance: build/custom_motor_mount/provenance.json

Inspecting / managing the cache

bash
python -m llm_factory list                  # show every cached user.* factory
python -m llm_factory show-merged           # built-ins + user.* merged registry
cat user_factories/simple_box_mount.py      # read the agent-authored CadQuery

To force a regeneration, delete the matching .py plus its entry in user_factories/registry.json. See docs/llm_factory_guide.md for the full feature reference.

Demos

bash
# Built-in factories only (no LLM needed)
conda run -n cad python -m cad_assembly.pipeline run demos/motor_bracket.yaml --build-root build/
conda run -n cad python -m cad_assembly.pipeline run demos/reducer.yaml      --build-root build/

# Phase 1 — exercises the user.* synth pre-stage (needs config.yaml)
conda run -n cad python -m cad_assembly.pipeline run demos/custom_bracket.yaml      --build-root build/
conda run -n cad python -m cad_assembly.pipeline run demos/custom_motor_mount.yaml  --build-root build/

# Or use the smoke-test script that exercises the built-in demos
conda run -n cad python demos/smoke_test.py

Roadmap

  • ✅ Phase 0.5 — Standalone agent. agent/ + llm/ shipped. NL → spec → STEP via python -m agent.
  • ✅ Phase 1 — LLM-driven custom-part factory. A user.* namespace where the LLM writes CadQuery for parts the 13 built-ins can't cover. Sandboxed, validated, cached. Implementation lives in llm_factory/; user-facing guide at docs/llm_factory_guide.md.
  • ✅ Phase 1.5 — Foundations for the new Phase 2.
    • 1.5.1 — dropped the tree2code/ middle layer; assemble runs in-process.
    • 1.5.2 — face_to_face mate gains u/v/offset_normal so multiple parts can share one base port.
    • 1.5.3 — geometry-aware verify: clash.json + dof.json + next to the STEP.

See CLAUDE.md for design constraints (fail-fast, layout invariants).

Documentation

  • docs/agent.md — agent architecture, configuration, and CLI reference.
  • docs/llm_factory_guide.md — Phase 1 user guide: how the agent writes custom parts (user.*) on demand.
  • ROADMAP.md — phased plan and checklists.
  • docs/phase1_llm_factory.md — Phase 1 architecture / design notes.
  • docs/phase2_step_gen.md — step-by-step graph generation design.
  • README_CN.md — 中文 README.
  • agent/prompts/system.md — canonical pipeline reference (factories, mates, ports, axioms, user.* rules).

Requirements

Python 3.10+, CadQuery, cq_warehouse, cq_gears, PyYAML, Jinja2, jsonschema, httpx.

License

MIT

相关文章0

暂无相关文章

verify.json + clash.json + dof.json + <tree_id>.png
6provenanceprovenance.json
<id>.png
  • 1.5.4 — spec snapshot copied to build/<id>/spec.yaml.
  • 1.5.5 — curved-geometry few-shots (spline + revolve, loft) for user.* synth.
  • 1.5.6 — single-solid invariant (solid_count == 1) + safe_union helper + port-geometry consistency check (bore / shaft / flat_face references real geometry on the as-built solid).
  • Phase 2 — Planner + step-by-step + reflect (in design). Replaces the single-shot decompose with a plan + per-step apply + visual reflect loop. See ROADMAP.md.
  • Phase 3 — URDF export (deferred). mate_type → joint_type mapping for robotics simulators.