292 lines
14 KiB
Python
292 lines
14 KiB
Python
"""②理解层的核心流程,供命令行脚本(generate_from_text.py/modify_part.py)和
|
||
交互式入口(cadmind.py)共用,避免每个入口各自维护一份重试/校验逻辑。
|
||
|
||
三级兜底,保证不管发生什么都不会空手返回给用户:
|
||
1. 正常方式(完整能力清单) + 重试 MAX_RETRIES 次
|
||
2. 仍失败 -> 降级重试一次:明确告诉模型别再用容易出错的精细能力,
|
||
换最基础的能力拼一个外观近似的结构,哪怕功能上不完善也行
|
||
3. 降级也失败 -> 生成时:退回一个占位方块,报告里如实写清楚原因;
|
||
修改时:保留原零件不变,报告修改未生效的原因(不能用占位覆盖一个本来能用的零件)
|
||
"""
|
||
|
||
import json
|
||
from pathlib import Path
|
||
|
||
from openai import OpenAI
|
||
|
||
from .executor import IRError, ir_from_report, run_ir
|
||
from .llm_client import LLMResponseError, MODEL, build_user_content, call_json
|
||
from .prompt_builder import build_modification_system_prompt, build_system_prompt
|
||
from .registry import load_registry
|
||
from .validation import safe_name
|
||
|
||
MAX_RETRIES = 3
|
||
|
||
DEGRADED_INSTRUCTION = (
|
||
"注意:前面按正常方式生成反复失败,错误信息如下。这一次请降级处理:只使用最基础、"
|
||
"最不容易出错的能力(sketch_circle/sketch_rect/extrude/revolve/boolean_combine/"
|
||
"translate/rotate/sphere等),不要使用 sphere_grooved、ring_captured 这类精细机关能力,"
|
||
"做一个尽量贴近原描述外观的近似结构就行——哪怕不能实现'真正能转动/无法拆分'这类精细"
|
||
"功能也完全可以,只要求这次必须顺利生成成功,绝不能再失败。\n\n错误信息:\n{reason}"
|
||
)
|
||
|
||
|
||
class PipelineError(Exception):
|
||
"""Pipeline stopped; quality jobs carry an ID for durable manual recovery."""
|
||
|
||
def __init__(self, message, *, job_id=None):
|
||
super().__init__(message)
|
||
self.job_id = job_id
|
||
|
||
|
||
def _autofix_known_mistakes(ir: dict) -> dict:
|
||
"""已知的、GPT反复重试也纠正不了的错误模式,直接由程序自动修正,不依赖模型自我纠正。
|
||
|
||
目前已知一种: sphere_grooved 的第一次调用(target应留空)被GPT按默认链式规则
|
||
误传成了上一步的base/pillar等实体。这个模式一旦出现,规则是确定的(第一次出现
|
||
的sphere_grooved、且target不是另一个sphere_grooved的结果,就该清空target),
|
||
没必要每次都指望模型自己想明白。
|
||
|
||
注意: target字段"完全没写"和"显式写了null"在这里必须同等对待,都要检查——
|
||
只看 op.get("target") 拿到的是不是None不够,因为字段缺失时执行器会自己默认
|
||
用上一步的结果去补,跟误传了一个错误值是同一个bug,不能因为拿到的值恰好是
|
||
None就误判成"已经是对的、不用管"。
|
||
"""
|
||
seen_sphere_grooved_ids = set()
|
||
for op in ir.get("operations", []):
|
||
if op.get("op") != "sphere_grooved":
|
||
continue
|
||
target = op.get("target")
|
||
if target not in seen_sphere_grooved_ids:
|
||
op["target"] = None
|
||
seen_sphere_grooved_ids.add(op.get("id"))
|
||
return ir
|
||
|
||
|
||
def _attempt_once(client, messages, base_dir: Path, registry: dict, default_name: str):
|
||
"""跑一次'调用大模型 -> 执行IR'。成功返回(report, None, ir),失败返回(None, 错误反馈文本, ir)。"""
|
||
try:
|
||
ir = call_json(client, messages)
|
||
except LLMResponseError as e:
|
||
print(f"[模型输出异常] {e}")
|
||
return None, f"上一次输出被截断/无法解析成JSON: {e}\n请精简描述涉及的操作数量,确保能一次性完整输出JSON。", {}
|
||
ir = _autofix_known_mistakes(ir)
|
||
|
||
if not ir.get("operations"):
|
||
reasons = "; ".join(ir.get("assumptions", [])) or "未说明原因"
|
||
return None, f"模型判断当前能力库无法表达此结构: {reasons}", ir
|
||
|
||
print(f"[理解层] 零件: {ir.get('name')}")
|
||
print(f"[理解层] 操作序列: {[op['op'] for op in ir['operations']]}")
|
||
if ir.get("assumptions"):
|
||
print("[理解层] 自行假设的参数:")
|
||
for a in ir["assumptions"]:
|
||
print(f" - {a}")
|
||
|
||
try:
|
||
name = safe_name(ir.get("name", default_name))
|
||
except ValueError as exc:
|
||
return None, str(exc), ir
|
||
out_dir = base_dir / "output" / name
|
||
try:
|
||
report = run_ir(ir, registry, out_dir)
|
||
except IRError as e:
|
||
print(f"[校验失败] 操作[{e.op_index}] '{e.op_name}': {e.errors}")
|
||
feedback = (
|
||
f"操作[{e.op_index}] '{e.op_name}' 校验失败: {e.errors}\n"
|
||
f"你之前输出的完整IR:\n{json.dumps(ir, ensure_ascii=False)}"
|
||
)
|
||
return None, feedback, ir
|
||
|
||
return report, None, ir
|
||
|
||
|
||
def _finalize(report: dict, base_dir: Path, ir: dict, user_text: str, extra: dict) -> dict:
|
||
report["llm_model"] = MODEL
|
||
report["llm_assumptions"] = ir.get("assumptions", [])
|
||
report["source_description"] = user_text
|
||
report.update(extra)
|
||
out_dir = base_dir / "output" / report["part_name"]
|
||
(out_dir / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
return report
|
||
|
||
|
||
def _fallback_placeholder(name: str, base_dir: Path, reason: str, source_description: str) -> dict:
|
||
"""最后一道保险:正常方式和降级方式都失败时,也绝不能空手返回——落一个占位方块,
|
||
report里如实写清楚这不是真实结果、原因是什么、用户原本要的是什么。
|
||
"""
|
||
registry = load_registry(base_dir / "capabilities")
|
||
placeholder_ir = {
|
||
"name": name,
|
||
"operations": [
|
||
{"op": "sketch_rect", "id": "placeholder_sketch", "params": {"width": 50, "height": 50, "x_offset": -25, "y_offset": -25}},
|
||
{"op": "extrude", "id": "placeholder_body", "target": "placeholder_sketch", "params": {"amount": 50}},
|
||
],
|
||
"output": "placeholder_body",
|
||
}
|
||
out_dir = base_dir / "output" / name
|
||
report = run_ir(placeholder_ir, registry, out_dir)
|
||
report["is_fallback_placeholder"] = True
|
||
report["fallback_reason"] = reason
|
||
report["source_description"] = source_description
|
||
report["llm_model"] = MODEL
|
||
(out_dir / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
return report
|
||
|
||
|
||
def _client(base_dir: Path) -> OpenAI:
|
||
import os
|
||
|
||
api_key = os.environ.get("OPENAI_API_KEY")
|
||
if not api_key:
|
||
raise PipelineError("未找到 OPENAI_API_KEY,请检查 .env 文件")
|
||
return OpenAI(api_key=api_key)
|
||
|
||
|
||
def generate_from_description(user_text: str, base_dir: Path, image_base64: str | list[str] | None = None) -> dict:
|
||
"""一句话描述(可选附一张参考图) -> 调用大模型生成IR -> 校验执行 -> 返回report。
|
||
三级兜底,不会空手返回。"""
|
||
client = _client(base_dir)
|
||
system_prompt = build_system_prompt(base_dir / "capabilities", user_text)
|
||
registry = load_registry(base_dir / "capabilities")
|
||
user_content = build_user_content(user_text, image_base64)
|
||
messages_base = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}]
|
||
|
||
error_feedback = None
|
||
last_name = "unnamed_part"
|
||
for attempt in range(1, MAX_RETRIES + 2):
|
||
messages = list(messages_base)
|
||
if error_feedback:
|
||
messages.append({"role": "user", "content": f"上一次生成的IR校验/执行失败,请修正后重新输出完整JSON:\n{error_feedback}"})
|
||
|
||
print(f"[理解层] 第{attempt}次调用 {MODEL} 分析需求...")
|
||
report, error_feedback, ir = _attempt_once(client, messages, base_dir, registry, last_name)
|
||
if ir.get("name"):
|
||
last_name = ir["name"]
|
||
if report is not None:
|
||
return _finalize(report, base_dir, ir, user_text, {})
|
||
|
||
print("[降级重试] 正常方式反复失败,改用最基础能力拼一个近似结果,不再追求精细机关...")
|
||
degraded_messages = list(messages_base) + [
|
||
{"role": "user", "content": DEGRADED_INSTRUCTION.format(reason=error_feedback)}
|
||
]
|
||
report, error_feedback2, ir2 = _attempt_once(client, degraded_messages, base_dir, registry, last_name)
|
||
if report is not None:
|
||
return _finalize(report, base_dir, ir2, user_text, {"degraded_fallback": True, "degraded_reason": error_feedback})
|
||
|
||
print(f"[降级也失败] {error_feedback2};最终退回占位模型,保证不空手返回")
|
||
return _fallback_placeholder(ir2.get("name", last_name), base_dir, error_feedback2, user_text)
|
||
|
||
|
||
def generate_from_description_best(user_text: str, base_dir: Path, image_base64: str | list[str] | None = None,
|
||
mode: str | None = None) -> dict:
|
||
"""默认分阶段质量建模;legacy 显式选择旧的降级流程。"""
|
||
import os
|
||
selected = mode or os.getenv("CADMIND_MODE", "quality")
|
||
if selected == "quality":
|
||
from .quality_pipeline import generate_quality
|
||
return generate_quality(user_text, base_dir, image_base64)
|
||
if selected != "legacy":
|
||
raise PipelineError("mode 只能为 quality 或 legacy")
|
||
from .agent_pipeline import AgentGenerationError, generate_from_description_agentic
|
||
|
||
try:
|
||
report = generate_from_description_agentic(user_text, base_dir, image_base64=image_base64)
|
||
report.setdefault("degraded_fallback", False)
|
||
report.setdefault("is_fallback_placeholder", False)
|
||
return report
|
||
except AgentGenerationError as e:
|
||
print(f"[agent模式未收敛] {e};退回一次性生成流程")
|
||
except Exception as e: # noqa: BLE001 - agent模式是新代码,任何异常都不能让用户空手而归
|
||
print(f"[agent模式异常] {e};退回一次性生成流程")
|
||
|
||
return generate_from_description(user_text, base_dir, image_base64=image_base64)
|
||
|
||
|
||
def modify_existing_part(part_name: str, change_request: str, base_dir: Path, image_base64: str | list[str] | None = None, *, config=None, job_callback=None) -> dict:
|
||
"""在已有零件的IR基础上按修改要求重新生成。三级兜底,但兜底策略跟生成不同:
|
||
修改失败时不能用占位方块覆盖一个本来能用的零件,最坏情况下保留原零件不变。
|
||
"""
|
||
try:
|
||
safe_name(part_name)
|
||
except ValueError as exc:
|
||
raise PipelineError(str(exc)) from exc
|
||
base_dir = Path(base_dir)
|
||
out_dir = base_dir / "output" / part_name
|
||
report_path = out_dir / "report.json"
|
||
if not report_path.exists():
|
||
raise PipelineError(f"找不到 {report_path},零件名不对,或者这个零件不是用理解层管线生成的")
|
||
|
||
old_report = json.loads(report_path.read_text(encoding="utf-8"))
|
||
if old_report.get("quality_mode"):
|
||
from .quality_pipeline import generate_quality
|
||
import base64
|
||
source_images = []
|
||
request_path = out_dir / "request.json"
|
||
if request_path.exists():
|
||
saved = json.loads(request_path.read_text(encoding="utf-8"))
|
||
source_images = [base64.b64encode((out_dir / Path(item["file"]).name).read_bytes()).decode()
|
||
for item in saved.get("images", [])]
|
||
# The new version gets the original evidence plus the explicit change; the old version is immutable.
|
||
text = ("原始请求:" + old_report.get("source_description", "") + "\n用户本次明确修改(优先于原图旧尺寸):"
|
||
+ change_request + "\n保留未要求修改的结构。旧模型操作序列供编辑参考:"
|
||
+ json.dumps(ir_from_report(old_report), ensure_ascii=False))
|
||
result = generate_quality(text, base_dir, image_base64 if image_base64 else source_images,
|
||
config=config, job_callback=job_callback)
|
||
result["parent_part"] = part_name
|
||
result["modification_history"] = old_report.get("modification_history", []) + [change_request]
|
||
from .job import write_json
|
||
write_json(Path(result["step_file"]).parent / "report.json", result)
|
||
return result
|
||
if "output_id" not in old_report:
|
||
raise PipelineError("这份report.json是旧版本生成的,没有target记录,无法还原成IR做修改")
|
||
|
||
existing_ir = ir_from_report(old_report)
|
||
|
||
client = _client(base_dir)
|
||
system_prompt = build_modification_system_prompt(base_dir / "capabilities", change_request)
|
||
registry = load_registry(base_dir / "capabilities")
|
||
|
||
user_text = f"已生成零件的完整IR:\n{json.dumps(existing_ir, ensure_ascii=False)}\n\n修改要求: {change_request}"
|
||
messages_base = [
|
||
{"role": "system", "content": system_prompt},
|
||
{"role": "user", "content": build_user_content(user_text, image_base64)},
|
||
]
|
||
|
||
def finalize_modify(report, ir, extra):
|
||
report["llm_model"] = MODEL
|
||
report["llm_assumptions"] = ir.get("assumptions", [])
|
||
report["source_description"] = old_report.get("source_description")
|
||
history = old_report.get("modification_history", [])
|
||
history.append(change_request)
|
||
report["modification_history"] = history
|
||
report.update(extra)
|
||
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
return report
|
||
|
||
error_feedback = None
|
||
for attempt in range(1, MAX_RETRIES + 2):
|
||
messages = list(messages_base)
|
||
if error_feedback:
|
||
messages.append({"role": "user", "content": f"上一次修改后的IR校验/执行失败,请修正后重新输出完整JSON:\n{error_feedback}"})
|
||
|
||
print(f"[理解层] 第{attempt}次调用 {MODEL} 分析修改要求...")
|
||
report, error_feedback, ir = _attempt_once(client, messages, base_dir, registry, part_name)
|
||
if report is not None:
|
||
return finalize_modify(report, ir, {})
|
||
|
||
print("[降级重试] 正常方式反复失败,改用最基础能力尝试应用这次修改...")
|
||
degraded_messages = list(messages_base) + [
|
||
{"role": "user", "content": DEGRADED_INSTRUCTION.format(reason=error_feedback)}
|
||
]
|
||
report, error_feedback2, ir2 = _attempt_once(client, degraded_messages, base_dir, registry, part_name)
|
||
if report is not None:
|
||
return finalize_modify(report, ir2, {"degraded_fallback": True, "degraded_reason": error_feedback})
|
||
|
||
print(f"[降级也失败] {error_feedback2};保留原零件不变,不用占位覆盖一个本来能用的零件")
|
||
old_report["modification_failed"] = True
|
||
old_report["modification_failed_reason"] = error_feedback2
|
||
old_report.setdefault("modification_history_failed", []).append(change_request)
|
||
report_path.write_text(json.dumps(old_report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
return old_report
|