Spaces:
Running on Zero

sid1-agentic-search / render.py
masterofaudio2077's picture
Agentic search demo: trace viewer (data build pending)
00df568 verified
Raw History Blame Contribute Delete
6.49 kB
"""Pure HTML builders for the demo UI. Every piece of model or Wikipedia text goes through esc(); nothing else touches the page."""
import html
NODES = ("generate", "tools", "report")
ERRORS = {
"truncated": "The turn ran out of its token budget.",
"unclosed_think": "The model never closed its thinking.",
"no_tool_call": "The model answered without calling a tool.",
"report_not_alone": "The report call was mixed with other calls.",
"ctx_full": "The context window filled up.",
"no_report": "The turn limit was reached without a report.",
}
def esc(x):
return html.escape(str(x), quote=True)
def loop_diagram(active=None, done=False):
"""The agent graph as a small inline SVG. `active` is the node that is running now: generate, tools or report."""
def box(name, label, x, y):
cls = "node on" if active == name else "node"
return (f'<g class="{cls}"><rect x="{x}" y="{y}" width="96" height="34" rx="4"/>'
f'<text x="{x + 48}" y="{y + 22}" text-anchor="middle">{label}</text></g>')
return (
f'<svg class="loop{" done" if done else ""}" viewBox="0 0 400 96" role="img" aria-label="Agent loop: generate, then tools, repeated until a report">'
'<defs><marker id="arr" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 8 4 0 8z"/></marker></defs>'
'<path class="edge" d="M112 17H152" marker-end="url(#arr)"/>'
'<path class="edge" d="M200 34V62H64V34" marker-end="url(#arr)" transform="translate(0 0)"/>'
'<path class="edge" d="M248 17H288" marker-end="url(#arr)"/>'
+ box("generate", "generate", 16, 0) + box("tools", "tools", 152, 0) + box("report", "report", 288, 0)
+ '<text class="edge-label" x="132" y="82" text-anchor="middle">repeat until report</text></svg>'
)
def _chips(calls):
out = []
for c in calls:
a = c["args"]
arg = a.get("query") or a.get("doc_id") or ", ".join(a.get("doc_ids", []))
out.append(f'<span class="chip"><b>{esc(c["name"])}</b> <span>{esc(arg)}</span></span>')
return "".join(out)
def _hits(r):
if r["name"] == "read":
h = r["hits"]
if not h:
return f'<p class="note">{esc(r["text"])}</p>'
return f'<p class="read"><b>{esc(h[0]["title"])}</b> <code>{esc(h[0]["doc_id"])}</code><br>{esc(h[0]["excerpt"])}</p>'
if not r["hits"]:
return '<p class="note">No results.</p>'
return "<ol class=\"hits\">" + "".join(f'<li><b>{esc(h["title"])}</b> <code>{esc(h["doc_id"])}</code></li>' for h in r["hits"]) + "</ol>"
def render_trace(events, running=False):
"""events: the list yielded by agent.run_agent so far. Returns the diagram plus one <details> per turn."""
turns, results, end, start = {}, {}, None, None
for e in events:
if e["type"] == "start":
start = e
elif e["type"] == "turn":
turns[e["turn"]] = e
elif e["type"] == "results":
results[e["turn"]] = e["results"]
elif e["type"] == "end":
end = e
last = events[-1] if events else None
active = None
if running and last:
active = "tools" if last["type"] == "turn" and last["calls"] and last["calls"][0]["name"] != "report" else "generate"
elif end and end["report"] is not None:
active = "report"
parts = [f'<div class="diagram">{loop_diagram(active, done=end is not None)}</div>']
if not events:
parts.append('<p class="empty">Pick an example or type a question, then press Replay Example or Run Live. Each turn of the agent shows up here.</p>')
for n in sorted(turns):
t = turns[n]
searches = [c for c in t["calls"] if c["name"] != "report"]
title = "Report" if t["calls"] and t["calls"][0]["name"] == "report" else (f'{len(searches)} {"call" if len(searches) == 1 else "calls"}' if searches else "No tool call")
bad = f' <span class="bad">{esc(ERRORS.get(t["error"], t["error"]))}</span>' if t["error"] else ""
body = []
if t["thinking"]:
body.append(f'<details class="think"><summary>Thinking</summary><p>{esc(t["thinking"])}</p></details>')
body.append(f'<div class="chips">{_chips(t["calls"])}</div>')
for r in results.get(n, []):
body.append(f'<div class="result"><h4><span class="mono">{esc(r["name"])}</span> {esc(r["args"].get("query") or r["args"].get("doc_id") or "")}</h4>{_hits(r)}</div>')
opened = " open" if n == max(turns) else ""
parts.append(f'<details class="turn"{opened}><summary><span class="n">Turn {n}</span><span class="what">{esc(title)}</span><span class="tok">{t["gen_tokens"]} tokens</span></summary>{"".join(body)}{bad}</details>')
if end:
why = f'<p class="bad">{esc(ERRORS.get(end["err"], end["err"]))}</p>' if end["err"] else ""
parts.append(f'<p class="summary">{end["turns"]} turns · {end["gen_tokens"]} generated tokens · {end["total_tokens"]} tokens of context used</p>{why}')
return f'<div class="trace" aria-live="polite">{"".join(parts)}</div>'
def _rows(ids, lookup, gold):
if not ids:
return '<p class="empty">Nothing yet.</p>'
g = set(gold or [])
rows = []
for i, d in enumerate(ids, 1):
title, text = lookup(d)
mark = ""
if gold:
mark = '<span class="gold" title="Relevant paragraph">relevant</span>' if d in g else '<span class="miss">not relevant</span>'
rows.append(f'<li><span class="rank">{i}</span><div><p class="t"><b>{esc(title)}</b> <code>{esc(d)}</code> {mark}</p><p class="x">{esc(text)}</p></div></li>')
return f'<ol class="rows">{"".join(rows)}</ol>'
def render_compare(report, baseline, lookup, gold=None, metrics=None):
"""Agent report beside the vector-only top 10. gold/metrics only when the question has known relevant paragraphs."""
def head(name, score):
s = f'<span class="score">NDCG {score:.2f}</span>' if score is not None else ""
return f'<h3>{name}{s}</h3>'
a = metrics.get("agent") if metrics else None
b = metrics.get("baseline") if metrics else None
return (f'<div class="compare"><section>{head("Agent Report", a)}{_rows(report, lookup, gold)}</section>'
f'<section>{head("Vector-Only Top 10", b)}{_rows(baseline, lookup, gold)}</section></div>')
def render_status(text, kind="info"):
return f'<p class="status {esc(kind)}" role="status">{esc(text)}</p>'