解决三个缺口:① 放大没复用标定/瓦片数学(LLM 一次 zoom 只出一张,宽区域仍读不清);
②「看清没」由 VLM 自评(易过度自信/幻觉);③ 只能按 handle / 手算 bbox 指认,
图上看到但没 handle 的东西指认不了。
核心思路:把「放大」升级成一个语义化工具——LLM 只指认「要看哪里」,由 agent 复用
tiling.py 的标定数学算出该切几张、每张覆盖多大,用构造保证可读。
新增 dwg_review/inspect.py(agent 侧,不编 DLL):
- TOOL_SCHEMA:inspect_region(target, purpose);target 三形态 {handle} / {window} /
{label,cx,cy,span},purpose = text(8px) / line(6px)。
- InspectState:单图框内「截图标签 → 世界可见范围」登记表,支持逐级下钻
(返回的 inspect-N 可继续作为 label 指认)。
- resolve_target / _point_box:label+cx+cy → WCS。cy 是图像坐标(上→下),
世界 y 必须翻转(y = y2 - cy*H)——单测专门钉住。
- plan_tiles:复用 world_per_px + tiles_for_box + subdivide;超 INSPECT_MAX_TILES(4)
则硬失败并给出「缩小 target / 分多次请求」的指引(不静默降级);拿不到比例/像素
则退回单张并如实告知。
关键几何:CAD 的 _.ZOOM _W 是等比适配(不拉伸),故「截图上的归一化坐标」必须按
max(W/ew, H/eh) 反算真实可见范围(新增 tiling.visible_box)——直接用送进去的窗口会偏。
zoom_to_window 返回的 view 是「加过 margin 的窗口」,不是可见范围,不能混用。
证据层配套:evidence_model.make_image(..., window=) 记录每张图的可见世界范围;
capture_images 用 view_px(overall 图原始像素)+ visible_box 逐张登记。
子循环接入:_run_readonly_tool 在只读白名单校验之前拦截 inspect_region(它不在
READ_ONLY_TOOLS 里,内部只调白名单内的只读 MCP 工具);_review_tools 启用时用
inspect_region 取代三个裸视口工具;inspect_region 计入 _VIEW_TOOLS → 结束复位视口。
配置:INSPECT_ENABLED(True) / INSPECT_MAX_TILES(4)。
端到端实测(真实图纸 1 图框):取证与审查两阶段均在最大化态、结束精确还原(4 项 PASS);
LLM 的 11 次取证调用里 2 次是 inspect_region,且都显式给 window + purpose:"text"
(x[20000,115000] y[-6500,3000],即 A0 图框底部横条=标题栏所在)。
验收口径达成:报告报出标题栏乱码 ???????????????,而 get_text_content 对全图返回 0 条文字
(本图文字全在块/自定义实体内)→ 块内文字是被视觉放大读出来的。
pytest 343 passed。
190 lines
7.6 KiB
Python
190 lines
7.6 KiB
Python
"""阶段 3:逐图框审查(LLM + 受控只读取证子循环)。
|
||
|
||
流程:
|
||
1. 用清单生成系统提示,喂入结构化证据 + 截图。
|
||
2. LLM 若请求只读取证工具 → 执行后把观测回灌,再问(有界循环)。
|
||
3. LLM 不再请求工具时,其输出(受约束的 JSON)即为该图框的审查结论。
|
||
|
||
结论是**结构化对象** `{"summary": str, "issues": [dict], "raw": str}`,
|
||
不再依赖第二次 LLM 调用来抽取结构(见 `findings.parse_conclusion`)。
|
||
|
||
审查在**绘图区已最大化**的前提下进行(见 `evidence.maximized_drawing_area`),
|
||
子循环里的放大截图因此是高清的;若 LLM 动过视口,结束时复位到该图框整幅视图。
|
||
"""
|
||
|
||
import json
|
||
|
||
from .. import config, evidence_model, inspect
|
||
from ..cad_tools import READ_ONLY_TOOLS, is_write_tool
|
||
from ..findings import parse_conclusion
|
||
from ..llm_client import LlmClient, downsample_image_b64
|
||
from ..mcp_client import McpError, McpToolError, result_images, result_texts
|
||
|
||
# 单次审查回灌给 LLM 的图片数上限(控制视觉 token 成本)
|
||
_MAX_OBS_IMAGES = config.REVIEW_OBS_IMAGES
|
||
|
||
# 会改动视口的只读取证工具:用过之后须把视口复位,别把用户的 CAD 留在放大处
|
||
_VIEW_TOOLS = frozenset({"zoom_to_window", "zoom_to_entity", inspect.TOOL_NAME})
|
||
|
||
# 启用 inspect_region 时,这三个裸视口工具不再直接提供给 LLM(由 inspect_region 统一代理),
|
||
# 但仍留在只读白名单里,作为兜底仍然可被调用。
|
||
_RAW_VIEW_TOOLS = frozenset(
|
||
{"zoom_to_window", "zoom_to_entity", "get_viewport_screenshot"}
|
||
)
|
||
|
||
|
||
def evidence_payload(evidence):
|
||
"""把证据整理成给 LLM 的 JSON(剔除 base64 图片,避免撑爆上下文)。"""
|
||
frame = evidence.get("frame") or {}
|
||
return {
|
||
"source_type": evidence.get("source_type"),
|
||
"frame_index": evidence.get("index"),
|
||
"frame": {
|
||
k: frame.get(k)
|
||
for k in ("sheet_size", "kind", "layer", "bbox", "confidence")
|
||
},
|
||
"entities": evidence.get("entities"),
|
||
"texts": evidence.get("texts"),
|
||
"dimensions": evidence.get("dimensions"),
|
||
"blocks": evidence.get("blocks"),
|
||
"polylines": evidence.get("polylines"),
|
||
}
|
||
|
||
|
||
def _run_readonly_tool(ctx, name, args, image_budget, *, evidence=None, state=None):
|
||
"""执行一个只读取证工具,返回回灌给 LLM 的 content 列表。
|
||
|
||
`inspect_region` 是 **agent 侧虚拟工具**(不走 MCP),在只读白名单校验**之前**拦截:
|
||
它内部只调白名单内的只读 MCP 工具。
|
||
"""
|
||
if name == inspect.TOOL_NAME:
|
||
if not config.INSPECT_ENABLED or evidence is None or state is None:
|
||
return [{"type": "text", "text": "inspect_region 当前不可用。"}], image_budget
|
||
return inspect.inspect_region(ctx, evidence, args, image_budget, state)
|
||
|
||
if name not in READ_ONLY_TOOLS or is_write_tool(name):
|
||
return [{"type": "text", "text": f"工具 {name} 不在只读取证白名单内,已拒绝。"}], image_budget
|
||
|
||
try:
|
||
resp = ctx.tools.call(name, args)
|
||
except (McpError, McpToolError) as exc:
|
||
return [{"type": "text", "text": f"工具 {name} 执行失败: {exc}"}], image_budget
|
||
|
||
content = []
|
||
for text in result_texts(resp):
|
||
content.append({"type": "text", "text": text})
|
||
for b64, mime in result_images(resp):
|
||
if image_budget[0] <= 0:
|
||
content.append(
|
||
{
|
||
"type": "text",
|
||
"text": "(截图预算已用完,后续截图已省略;请基于已有信息给出结论,不要再请求截图。)",
|
||
}
|
||
)
|
||
break
|
||
image_budget[0] -= 1
|
||
nb, nm = downsample_image_b64(b64, mime)
|
||
content.append(LlmClient.image_content(nb, nm))
|
||
if not content:
|
||
content.append({"type": "text", "text": "(无返回内容)"})
|
||
return content, image_budget
|
||
|
||
|
||
def _review_tools(ctx):
|
||
"""审查子循环提供给 LLM 的工具 schema。
|
||
|
||
启用 `inspect_region` 时,用它**取代**三个裸视口工具(`zoom_to_window` /
|
||
`zoom_to_entity` / `get_viewport_screenshot`)——一个语义化入口比三个裸工具更好用,
|
||
且可读性由 agent 保证;关闭时维持原样(退回旧行为)。
|
||
"""
|
||
if config.INSPECT_ENABLED:
|
||
names = READ_ONLY_TOOLS - _RAW_VIEW_TOOLS
|
||
return ctx.tools.openai_tools(names=names) + [inspect.TOOL_SCHEMA]
|
||
return ctx.tools.openai_tools(names=READ_ONLY_TOOLS)
|
||
|
||
|
||
def _reset_viewport(ctx, evidence):
|
||
"""把视口复位到该图框的整幅视图(审查中的放大不应残留给用户)。"""
|
||
win = evidence.get("window")
|
||
if not win:
|
||
return
|
||
try:
|
||
ctx.tools.call("zoom_to_window", dict(win, margin=0.02))
|
||
except (McpError, McpToolError):
|
||
pass
|
||
|
||
|
||
def review_frame(ctx, evidence, system_prompt, log=print):
|
||
"""审查单个图框,返回结构化结论 `{"summary", "issues", "raw"}`。
|
||
|
||
审查中的放大取证会改动视口,故在 finally 里复位——**仅当确实动过视口**
|
||
(LLM 只查结构化数据时不动用户视图)。
|
||
"""
|
||
view_changed = [False]
|
||
try:
|
||
return _review_frame(ctx, evidence, system_prompt, log, view_changed)
|
||
finally:
|
||
if view_changed[0]:
|
||
_reset_viewport(ctx, evidence)
|
||
|
||
|
||
def _review_frame(ctx, evidence, system_prompt, log, view_changed):
|
||
payload = evidence_payload(evidence)
|
||
user_content = [
|
||
{
|
||
"type": "text",
|
||
"text": "以下是该图框的审查输入数据(JSON):\n"
|
||
+ json.dumps(payload, ensure_ascii=False, indent=2),
|
||
}
|
||
]
|
||
for img in evidence_model.evidence_images(evidence):
|
||
nb, nm = downsample_image_b64(img["b64"], img.get("mime") or "image/png")
|
||
label = img.get("label")
|
||
if label:
|
||
user_content.append({"type": "text", "text": f"(截图:{label})"})
|
||
user_content.append(LlmClient.image_content(nb, nm))
|
||
|
||
messages = [
|
||
{"role": "system", "content": system_prompt},
|
||
{"role": "user", "content": user_content},
|
||
]
|
||
|
||
tools_schema = _review_tools(ctx)
|
||
image_budget = [_MAX_OBS_IMAGES]
|
||
state = inspect.InspectState(evidence)
|
||
|
||
for _ in range(max(0, ctx.max_iters)):
|
||
resp = ctx.llm.chat(messages, tools=tools_schema)
|
||
msg = resp.choices[0].message
|
||
messages.append(msg)
|
||
|
||
# 仅在「不再请求工具」的回合解析结论;中间工具回合的 content 永不解析
|
||
if not msg.tool_calls:
|
||
return parse_conclusion(msg.content or "", log=log)
|
||
|
||
for tool_call in msg.tool_calls:
|
||
name = tool_call.function.name
|
||
try:
|
||
args = json.loads(tool_call.function.arguments or "{}")
|
||
except json.JSONDecodeError:
|
||
args = {}
|
||
log(f" [取证] {name} {args if args else ''}")
|
||
if name in _VIEW_TOOLS:
|
||
view_changed[0] = True
|
||
content, image_budget = _run_readonly_tool(
|
||
ctx, name, args, image_budget, evidence=evidence, state=state
|
||
)
|
||
messages.append(
|
||
{"role": "tool", "tool_call_id": tool_call.id, "content": content}
|
||
)
|
||
|
||
# 达到回合上限:强制收口(不传 tools,保证不再请求工具,输出必为终稿 JSON)
|
||
messages.append(
|
||
{
|
||
"role": "user",
|
||
"content": "已达到取证回合上限,请基于现有信息直接给出该图框的审查结论(JSON)。",
|
||
}
|
||
)
|
||
resp = ctx.llm.chat(messages)
|
||
return parse_conclusion(resp.choices[0].message.content or "", log=log)
|