"""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'' f'{label}') return ( f'' '' '' '' '' + box("generate", "generate", 16, 0) + box("tools", "tools", 152, 0) + box("report", "report", 288, 0) + 'repeat until report' ) 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'{esc(c["name"])} {esc(arg)}') return "".join(out) def _hits(r): if r["name"] == "read": h = r["hits"] if not h: return f'

{esc(r["text"])}

' return f'

{esc(h[0]["title"])} {esc(h[0]["doc_id"])}
{esc(h[0]["excerpt"])}

' if not r["hits"]: return '

No results.

' return "
    " + "".join(f'
  1. {esc(h["title"])} {esc(h["doc_id"])}
  2. ' for h in r["hits"]) + "
" def render_trace(events, running=False): """events: the list yielded by agent.run_agent so far. Returns the diagram plus one
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'
{loop_diagram(active, done=end is not None)}
'] if not events: parts.append('

Pick an example or type a question, then press Replay Example or Run Live. Each turn of the agent shows up here.

') 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' {esc(ERRORS.get(t["error"], t["error"]))}' if t["error"] else "" body = [] if t["thinking"]: body.append(f'
Thinking

{esc(t["thinking"])}

') body.append(f'
{_chips(t["calls"])}
') for r in results.get(n, []): body.append(f'

{esc(r["name"])} {esc(r["args"].get("query") or r["args"].get("doc_id") or "")}

{_hits(r)}
') opened = " open" if n == max(turns) else "" parts.append(f'
Turn {n}{esc(title)}{t["gen_tokens"]} tokens{"".join(body)}{bad}
') if end: why = f'

{esc(ERRORS.get(end["err"], end["err"]))}

' if end["err"] else "" parts.append(f'

{end["turns"]} turns · {end["gen_tokens"]} generated tokens · {end["total_tokens"]} tokens of context used

{why}') return f'
{"".join(parts)}
' def _rows(ids, lookup, gold): if not ids: return '

Nothing yet.

' g = set(gold or []) rows = [] for i, d in enumerate(ids, 1): title, text = lookup(d) mark = "" if gold: mark = 'relevant' if d in g else 'not relevant' rows.append(f'
  • {i}

    {esc(title)} {esc(d)} {mark}

    {esc(text)}

  • ') return f'
      {"".join(rows)}
    ' 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'NDCG {score:.2f}' if score is not None else "" return f'

    {name}{s}

    ' a = metrics.get("agent") if metrics else None b = metrics.get("baseline") if metrics else None return (f'
    {head("Agent Report", a)}{_rows(report, lookup, gold)}
    ' f'
    {head("Vector-Only Top 10", b)}{_rows(baseline, lookup, gold)}
    ') def render_status(text, kind="info"): return f'

    {esc(text)}

    '