| """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 |
|
|
|
|
| |
|
|
| 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}).""" |
|
|
|
|
| |
|
|
| 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] |
|
|
|
|
| |
|
|
| 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 |
|
|
|
|
| |
|
|
| 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]) |
|
|
| |
| 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"]) |
|
|
| |
| description = agent_a_describe(client, title, fig_num) |
| if not description: |
| continue |
| time.sleep(0.5) |
|
|
| |
| others = [r for r in figs if r["figure_number"] != fig_num] |
| rng.shuffle(others) |
| distractor_figs = others[:pool_size - 1] |
|
|
| |
| 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": ""}) |
|
|
| |
| 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() |
|
|