File size: 9,224 Bytes
7113658 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | """Task 4 — Agent-Agent Single-Round Communication.
Agent A (Designer) sees a patent figure and describes it using a structured schema.
Agent B (Maker) receives the description and selects the correct figure from a pool.
Conditions tested:
same_model — both agents use the same model (e.g., both Gemma 4)
cross_model — Agent A and B use different models (tests if description is grounded
in the drawing or in model-specific vocabulary)
The structured schema forces Agent A to produce parseable output:
{viewpoint, visible_components, spatial_relations, distinguishing_features}
This directly tests the McCarthy/mrCAD finding that design intent communication
requires both drawing (viewpoint, spatial_relations) and text (component vocabulary).
Usage:
python scripts/eval/agent_agent.py \
--enriched data/enriched/enriched_2022.parquet \
--n 18 \
--out results/agent_agent_results.json
"""
import argparse
import json
import re
import time
from collections import defaultdict
from pathlib import Path
import pandas as pd
import sys
sys.path.insert(0, str(Path(__file__).parent))
from provider import chat, get_client, get_model
# ── Schema ────────────────────────────────────────────────────────────────────
DESIGNER_PROMPT = """You are an engineer describing a technical patent figure to a colleague who cannot see it.
Patent title: {title}
This figure shows FIG. {fig_num} of the patent.
Describe the figure using ONLY this JSON schema — be specific enough that someone could identify this exact figure from among similar drawings:
{{
"viewpoint": "...",
"visible_components": ["...", "..."],
"spatial_relations": "...",
"distinguishing_features": "..."
}}
Rules:
- viewpoint: name the projection type (e.g. "front elevational view", "perspective view")
- visible_components: list 2-5 distinct parts visible in this specific view
- spatial_relations: describe how parts relate spatially (left/right/center/above/below)
- distinguishing_features: what makes THIS view unique vs. other views of the same object
Reply with the JSON only, no other text."""
MAKER_PROMPT = """You are selecting a patent figure based on a colleague's description.
The description is:
{description}
Below are {n} candidate figure descriptions (from the SAME patent but different views).
Which candidate BEST matches the description above?
{candidates}
Reply with just the number (1-{n})."""
# ── Viewpoint parsing (shared) ────────────────────────────────────────────────
def parse_vp(desc: str, fig_num: int) -> str:
pat = re.compile(
rf"FIG\.\s*{fig_num+1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
re.IGNORECASE,
)
m = pat.search(desc or "")
return m.group(1).strip().lower() if m else ""
def find_eligible_patents(df: pd.DataFrame, n: int, seed: int = 42) -> list[str]:
df["vp"] = df.apply(lambda r: parse_vp(r.get("drawing_description", ""), r["figure_number"]), axis=1)
has_persp = df.groupby("patent_id")["vp"].apply(lambda x: x.str.contains("perspective").any())
has_front = df.groupby("patent_id")["vp"].apply(
lambda x: (x.str.contains("front elev") | x.isin(["front elevation", "front plan"])).any()
)
eligible = has_persp.index[has_persp & has_front].tolist()
import random
rng = random.Random(seed)
rng.shuffle(eligible)
return eligible[:n]
# ── Agent calls ───────────────────────────────────────────────────────────────
def agent_a_describe(client, title: str, fig_num: int) -> dict | None:
"""Agent A: produce a structured description of the figure (text only — no image)."""
prompt = DESIGNER_PROMPT.format(title=title, fig_num=fig_num + 1)
msgs = [{"role": "user", "content": prompt}]
response = chat(client, msgs, max_tokens=300)
try:
m = re.search(r"\{.*\}", response, re.DOTALL)
if m:
return json.loads(m.group())
except Exception:
pass
return None
def agent_b_select(client, description: dict, candidates: list[dict]) -> int:
"""Agent B: select which candidate matches the description. Returns 0-indexed."""
desc_str = json.dumps(description, indent=2)
cand_lines = []
for i, c in enumerate(candidates, 1):
cand_lines.append(f"{i}. {json.dumps(c)}")
cands_str = "\n".join(cand_lines)
prompt = MAKER_PROMPT.format(
description=desc_str,
n=len(candidates),
candidates=cands_str,
)
msgs = [{"role": "user", "content": prompt}]
response = chat(client, msgs, max_tokens=10)
m = re.search(r"\b([1-9])\b", response)
return int(m.group()) - 1 if m else -1
# ── Main eval ─────────────────────────────────────────────────────────────────
def run(enriched_path: str, n: int, out_path: str, pool_size: int = 4, seed: int = 42):
import random
client = get_client()
df = pd.read_parquet(enriched_path)
eval_pids = find_eligible_patents(df, n, seed)
print(f"Evaluating {len(eval_pids)} patents | model: {get_model()}")
results = []
correct = total = 0
rng = random.Random(seed)
for pid in eval_pids:
group = df[df["patent_id"] == pid].sort_values("figure_number")
figs = group.to_dict("records")
title = str(group["patent_title"].iloc[0])
# Pick a target figure (front elevation if available, else random non-perspective)
front = [r for r in figs if "front elev" in r.get("vp", "")]
target = front[0] if front else rng.choice([r for r in figs if "perspective" not in r.get("vp", "")] or figs)
fig_num = int(target["figure_number"])
# Agent A: describe the target figure (text only — uses drawing_description context)
description = agent_a_describe(client, title, fig_num)
if not description:
continue
time.sleep(0.5)
# Build candidates: target + (pool_size-1) other views from the same patent
others = [r for r in figs if r["figure_number"] != fig_num]
rng.shuffle(others)
distractor_figs = others[:pool_size - 1]
# Describe distractors too (Agent A perspective)
candidates_data = []
correct_pos = rng.randint(0, pool_size - 1)
for i in range(pool_size):
if i == correct_pos:
candidates_data.append(description)
else:
if distractor_figs:
d_fig = distractor_figs.pop(0)
d_desc = agent_a_describe(client, title, int(d_fig["figure_number"]))
candidates_data.append(d_desc or {"viewpoint": "unknown", "visible_components": [], "spatial_relations": "", "distinguishing_features": ""})
time.sleep(0.3)
else:
candidates_data.append({"viewpoint": "unknown", "visible_components": [], "spatial_relations": "", "distinguishing_features": ""})
# Agent B: select the correct candidate
chosen = agent_b_select(client, description, candidates_data)
time.sleep(0.5)
ok = chosen == correct_pos
correct += int(ok)
total += 1
result = {
"patent_id": pid,
"patent_title": title,
"target_fig": fig_num,
"target_vp": target.get("vp", ""),
"description": description,
"correct_pos": correct_pos,
"chosen": chosen,
"correct": ok,
}
results.append(result)
print(f"[{pid}] {title[:40]} | vp: {target.get('vp','?')[:20]} | {'✓' if ok else '✗'} | running: {correct}/{total} ({correct/total:.1%})")
print(f"\n=== AGENT-AGENT RESULTS ===")
print(f"Same-model ({get_model()}) → same-model")
print(f"Accuracy: {correct}/{total} = {correct/total:.1%}")
print(f"Chance (pool={pool_size}): {1/pool_size:.1%}")
output = {
"model": get_model(),
"pool_size": pool_size,
"summary": {"acc": correct / max(total, 1), "n": total, "chance": 1/pool_size},
"results": results,
}
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w") as f:
json.dump(output, f, indent=2)
print(f"Results → {out_path}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
parser.add_argument("--n", type=int, default=18)
parser.add_argument("--pool", type=int, default=4)
parser.add_argument("--out", default="results/agent_agent_results.json")
args = parser.parse_args()
run(args.enriched, args.n, args.out, args.pool)
if __name__ == "__main__":
main()
|