Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ CEREBRAS_API_KEY=
# LLM_ANALYSIS_ITEMS=12 # concepts analysis asks for; bounds the reply's length
# LLM_RATE_IN= / LLM_RATE_OUT= # USD per million tokens; empty = unattributed

# The TypeScript diagram agent (reader/app/api/diagram). Set BOTH on the API to
# have concept diagrams drawn by a model calling validated tools; unset, codegen
# uses one-shot JSON. The reader project needs ARCVISUAL_INTERNAL_SECRET and
# OPENROUTER_API_KEY (optionally DIAGRAM_MODELS, LLM_REASONING_MAX_TOKENS).
# ARCVISUAL_DIAGRAM_AGENT_URL=https://arcvisual.vercel.app/api/diagram
# ARCVISUAL_INTERNAL_SECRET= # long random string, same value on both projects

# Formula-chain scenes allowed per paper. Past this, transform_chain proposals are
# re-cast as drawn concept diagrams of the same claim.
# ARCVISUAL_MAX_FORMULA_SCENES=2
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ jobs:
- run: pytest tests/test_render.py -m slow -v

reader:
name: reader typecheck + build
name: reader typecheck + tests + build
runs-on: ubuntu-latest
defaults:
run:
Expand All @@ -122,4 +122,5 @@ jobs:
cache-dependency-path: reader/package.json
- run: npm install --no-audit --no-fund
- run: npm run typecheck
- run: npm test
- run: npm run build
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,32 @@ Three decisions worth knowing:
`ANTHROPIC_BASE_URL` routes the Anthropic provider through any compatible gateway
(Dedalus Labs, a proxy). Same SDK, same model ids — a setting, not a fourth provider.

### The diagram agent (TypeScript, tool calling)

`reader/app/api/diagram` is a small TypeScript agent harness in the reader's
Next.js app; it runs server-side, so the key never reaches a browser. A model draws a
`concept_diagram` by calling one tool, `submit_diagram`, with the whole diagram:
elements, arrows and steps. The diagram is accepted as soon as it has no problems.
Otherwise the tool lists every problem at once: unknown ids, two elements in one
cell, marks on elements without items, or a runtime over 70 s. Runtime is measured
with `planConceptDiagram`, the code that animates the scene in the browser.

The tool is deliberately coarse. Each turn on the free endpoint costs about 15 s, and
a first version with separate `draw` / `script` / `finish` tools used all five turns
(75 s) because the model called them one at a time. Now the good case is one turn
and each fix one more. `reasoning_details` is passed back between turns.

Each call has its own timeout (90 s) within the step's deadline. A free model that
is slow, spent for the day or withdrawn hands over to the next model.
`lib/harness/harness.test.ts` covers all of this (`npm test`).

The Python pipeline calls the agent for a scene's first attempt when
`ARCVISUAL_DIAGRAM_AGENT_URL` and `ARCVISUAL_INTERNAL_SECRET` are set
(`arcvisual/generate/diagram_agent.py`). It passes the remaining step budget, and
validates the result exactly as it validates one-shot output. If the agent isn't
configured, is unreachable, runs out of time or returns nothing, the scene falls
back to one-shot generation.

### Long-context presets (100K–260K tokens per request)

`arcvisual/providers/longcontext_provider.py` is one OpenAI-compatible provider with
Expand Down
57 changes: 45 additions & 12 deletions arcvisual/analyze/single_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,10 @@ def _apply(
#: lists can be paired later without guessing.
kept_raw_indices: list[int] = []
for i, c in enumerate(raw.concepts):
section = resolve(c.section_id)
section, span = _ground(sb, resolve(c.section_id), c.quote)
if section is None:
report.concepts_dropped_ungrounded += 1
continue
span = span_for_text(section, c.quote)
if span is None:
report.concepts_dropped_ungrounded += 1
# Log the quote, not just the name. "dropped ungrounded concept 'X'" says
Expand Down Expand Up @@ -391,12 +390,8 @@ def _apply(
report.opportunities_dropped_unavailable += 1
log.info("dropped %s: no template in this build", o.archetype)
continue
section = resolve(o.section_id)
if section is None:
report.opportunities_dropped_ungrounded += 1
continue
span = span_for_text(section, o.quote)
if span is None:
section, span = _ground(sb, resolve(o.section_id), o.quote)
if section is None or span is None:
report.opportunities_dropped_ungrounded += 1
log.info("dropped ungrounded opportunity %r", o.claim[:60])
continue
Expand All @@ -405,10 +400,26 @@ def _apply(
# Fall back to any concept grounded in the same section rather than
# discarding a well-grounded proposal over a naming mismatch.
same_section = [c.id for c in concepts if c.span.section_id == section.id]
if not same_section:
report.opportunities_dropped_unknown_concept += 1
continue
concept_id = same_section[0]
if same_section:
concept_id = same_section[0]
else:
# The opportunity is grounded by its own quote; only its concept
# failed to ground. Dropping it here cascaded on a real paper: two
# of its concepts survived, so every opportunity elsewhere was lost
# and the article shipped with no visuals at all.
concept_id = f"c{len(raw.concepts) + i:03d}"
concept = Concept(
id=concept_id,
name=o.concept_name or o.claim[:60],
statement=o.claim,
span=span,
depends_on=[],
centrality=o.centrality,
)
concepts.append(concept)
by_cid[concept_id] = concept
name_to_id[_norm(concept.name)] = concept_id
report.concepts_kept = len(concepts)
candidates.append(
VisualOpportunity(
id=f"o{i:03d}",
Expand All @@ -426,6 +437,9 @@ def _apply(
report.opportunities_dropped_triage = len(candidates) - len(kept)
report.kept_opportunities = len(kept)

# Opportunities may have grounded concepts of their own; sections list them too.
for section in sb.sections:
section.concept_ids = [c.id for c in concepts if c.span.section_id == section.id]
sb.concepts = concepts
sb.opportunities = kept
sb.reading_order = _reading_order(sb, concepts)
Expand All @@ -437,6 +451,25 @@ def _apply(
return sb, report


def _ground(sb: Storyboard, claimed: Section | None, quote: str):
"""``(section, span)`` for a quote: the cited section first, then every other.

Models attribute a correct quote to a neighbouring section often enough that a
single-section search loses real, verbatim text. The span still points at the
exact characters wherever they were found; only the attribution is corrected.
Returns ``(claimed, None)`` when the quote is nowhere, ``(None, None)`` when no
section was resolvable and the quote is nowhere either.
"""
if claimed is not None and (span := span_for_text(claimed, quote)) is not None:
return claimed, span
for section in sb.sections:
if section is claimed:
continue
if (span := span_for_text(section, quote)) is not None:
return section, span
return claimed, None


def _section_resolver(sb: Storyboard):
"""Resolve a model's section reference to a real section.

Expand Down
10 changes: 9 additions & 1 deletion arcvisual/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
#: Bumped whenever pipeline behaviour changes in a way that should produce a
#: different article for the same paper. Part of the L3 cache key and of the
#: (paper_id, pipeline_version) idempotency key on `jobs`.
PIPELINE_VERSION = "0.3.0-diagrams"
PIPELINE_VERSION = "0.3.1-grounding"

#: Pinned render environment. Any change here invalidates every L2 artifact.
MANIM_VERSION = "0.18.1"
Expand Down Expand Up @@ -620,6 +620,12 @@ class Settings:
#: well under the platform's function limit (300s on Vercel Hobby): a scene
#: started near the end must still finish inside the same invocation.
step_budget_s: int = 200
#: The TypeScript diagram agent (reader/app/api/diagram). When set, concept
#: diagrams are drawn by a model calling validated tools instead of one-shot JSON;
#: on any failure codegen falls back to the one-shot path.
diagram_agent_url: str = ""
#: Shared with the agent route; it refuses every request without it.
internal_secret: str = ""

@property
def client_render(self) -> bool:
Expand Down Expand Up @@ -754,6 +760,8 @@ def settings() -> Settings:
strict_ownership=env("STRICT_OWNERSHIP", "1") != "0",
render_mode=env("ARCVISUAL_RENDER_MODE", "manim"),
step_budget_s=int(env("ARCVISUAL_STEP_BUDGET_S", "200")),
diagram_agent_url=env("ARCVISUAL_DIAGRAM_AGENT_URL", ""),
internal_secret=env("ARCVISUAL_INTERNAL_SECRET", ""),
budgets=Budgets(
scene_concurrency=int(env("ARCVISUAL_SCENE_CONCURRENCY", "4")),
max_formula_scenes=int(env("ARCVISUAL_MAX_FORMULA_SCENES", "2")),
Expand Down
54 changes: 44 additions & 10 deletions arcvisual/generate/codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,16 +200,20 @@ def generate_scene(
usage = Usage(attributed=True) # genuinely free: no call was made
notes = ["heuristic parameters — no model provider configured"]
else:
raw_params, beats, scrubbable, usage = _call_provider(
sb,
opportunity,
source_text,
provider=provider,
previous=previous,
findings=findings,
attempt=attempt,
)
notes = []
drawn = _draw_with_agent(sb, opportunity, provider, findings)
if drawn is not None:
raw_params, beats, scrubbable, usage, notes = drawn
else:
raw_params, beats, scrubbable, usage = _call_provider(
sb,
opportunity,
source_text,
provider=provider,
previous=previous,
findings=findings,
attempt=attempt,
)
notes = []
cost = usage.cost_usd

# Validate before building the spec: an invalid parameter set must not reach
Expand Down Expand Up @@ -267,6 +271,36 @@ def generate_scene(
)


def _draw_with_agent(
sb: Storyboard,
opportunity: VisualOpportunity,
provider: Provider,
findings: list[str] | None,
) -> tuple[dict[str, Any], list[Beat], bool, Usage, list[str]] | None:
"""A first-attempt concept diagram drawn by the TypeScript tool-calling agent.

Only the first attempt: a repair carries Gate 1's findings, which the one-shot
path already feeds back. None means "use the one-shot path" — the agent is not
configured, ran out of time, or returned no accepted diagram.
"""
from arcvisual.generate import diagram_agent

if opportunity.archetype is not Archetype.CONCEPT_DIAGRAM or findings:
return None
if not diagram_agent.configured():
return None
budget_fn = getattr(provider, "call_budget", None)
budget = float(budget_fn()) if callable(budget_fn) else 120.0
drawn = diagram_agent.draw(sb, opportunity, budget_s=budget)
if drawn is None:
return None
captions = drawn.captions or ["(diagram)"]
beats = fit_beats(captions, MIN_BEAT_S * 2 * len(captions))
note = f"drawn by the diagram agent in {drawn.turns} turn(s) on {drawn.model}"
# Tokens were spent by the agent's own calls, which report no price.
return drawn.params, beats, False, Usage(attributed=False), [note, *drawn.notes]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include paid agent calls in the scene budget

When the default free endpoint is exhausted or times out, the agent can fall through to paid models, but this reports zero cost and discards the token usage returned by the route. build_scene adds GenerateResult.cost_usd to its spend before checking the per-scene ceiling, so these paid turns are invisible to both the ceiling and the job total. Price the agent usage or prevent unpriced paid fallbacks.

Useful? React with 👍 / 👎.



def fit_beats(captions: list[str], total_s: float) -> list[Beat]:
"""Lay captions end to end across a runtime the template dictates.

Expand Down
103 changes: 103 additions & 0 deletions arcvisual/generate/diagram_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Client for the TypeScript diagram agent (``reader/app/api/diagram``).

The agent draws a ``concept_diagram`` by calling tools that validate each step as it
is taken, so a mistake costs one more turn of the same conversation rather than a
whole regeneration. This module only asks it for parameters; everything after that
(the template's validation, beats, Gate 1) is the same path one-shot codegen takes.

It never fails a scene. Not configured, out of time, unreachable, or no accepted
diagram: it returns None and codegen falls back to the one-shot call.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from typing import Any

from arcvisual.config import settings
from arcvisual.storyboard import Storyboard, VisualOpportunity

log = logging.getLogger(__name__)

#: Below this, the agent cannot finish a turn on the free endpoint (~15s each).
MIN_BUDGET_S = 30.0
#: Never ask for more: the route caps itself at 250s inside a 300s function.
MAX_BUDGET_S = 240.0


@dataclass
class AgentDiagram:
params: dict[str, Any]
captions: list[str]
turns: int
model: str
notes: list[str] = field(default_factory=list)


def configured() -> bool:
cfg = settings()
return bool(cfg.diagram_agent_url and cfg.internal_secret)


def draw(
sb: Storyboard,
opportunity: VisualOpportunity,
*,
budget_s: float,
client: Any = None,
) -> AgentDiagram | None:
"""Ask the agent for one diagram's parameters, or None to fall back."""
cfg = settings()
if not configured():
return None
budget_s = min(budget_s, MAX_BUDGET_S)
if budget_s < MIN_BUDGET_S:
log.info("diagram agent skipped: only %.0fs left", budget_s)
return None

section = sb.section(opportunity.span.section_id)
concept = sb.concept(opportunity.concept_id)
payload = {
"title": sb.paper.title,
"claim": opportunity.claim,
"concept": f"{concept.name} — {concept.statement}" if concept else "",
"quote": opportunity.span.resolve(section),
"section": section.raw[:12000],
"equations": [e.latex for e in sb.equations if e.span.section_id == section.id][
:6
],
"budget_s": round(budget_s),
}
headers = {"x-arcvisual-key": cfg.internal_secret}
try:
if client is None:
import httpx

# The agent bounds itself by budget_s; this only catches a hung network.
with httpx.Client(timeout=budget_s + 15) as http:
response = http.post(cfg.diagram_agent_url, json=payload, headers=headers)
else:
response = client.post(cfg.diagram_agent_url, json=payload, headers=headers)
except Exception as exc: # network trouble is a fallback, never a failed scene
log.warning("diagram agent unreachable: %s", exc)
return None
if response.status_code != 200:
log.warning(
"diagram agent answered %s: %s", response.status_code, response.text[:200]
)
return None
try:
body = response.json()
except ValueError:
return None
if not body.get("ok") or not isinstance(body.get("params"), dict):
log.info("diagram agent gave no diagram: %s", "; ".join(body.get("notes") or []))
return None
return AgentDiagram(
params=body["params"],
captions=[c for c in body.get("captions") or [] if isinstance(c, str)],
turns=int(body.get("turns") or 0),
model=str(body.get("model") or ""),
notes=[n for n in body.get("notes") or [] if isinstance(n, str)],
)
Loading
Loading