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
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ CEREBRAS_API_KEY=
# LLM_MAX_TOKENS=16384 # reasoning models bill thinking as output
# LLM_JSON_SCHEMA=1 # 0 = prompt the schema instead of enforcing it
# LLM_REASONING_EFFORT= # sent as reasoning_effort when set
# LLM_REASONING=1 # OpenRouter: reasoning {enabled: true}; 0 turns it off
# LLM_REASONING=1 # OpenRouter: reasoning {enabled: true} on diagram calls
# LLM_REASONING_ANALYZE=0 # also reason during analysis (slow: 112s vs 30s measured)
# LLM_REASONING_MAX_TOKENS=800 # reasoning cap per call; 0 = unbounded (66s vs 15s per diagram)
# LLM_CALL_TIMEOUT_S=120 # wall-clock cap per model call (replies are streamed)
# 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

# Formula-chain scenes allowed per paper. Past this, transform_chain proposals are
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,21 @@ silently ignores it (an OpenRouter upstream) falls back to the prompted path for
call rather than failing it. OpenRouter requests carry `require_parameters` so they
are only routed to upstreams that honour the schema.

On OpenRouter the Nemotron free endpoint leads the chain and is asked to reason
(`reasoning: {"enabled": true}`; `LLM_REASONING=0` turns it off). Every pipeline call
On OpenRouter the Nemotron free endpoint leads the chain. It reasons while drawing
diagrams (`reasoning: {"enabled": true}`; `LLM_REASONING=0` turns it off) but not while
analysing the paper, unless `LLM_REASONING_ANALYZE=1`. Measured on the free endpoint
(~86 tokens/s), the same analysis took 112 s with reasoning and 30 s without, and the
real one with reasoning ran past Vercel's 300 s function limit. Reasoning is also capped at
800 tokens per call (`LLM_REASONING_MAX_TOKENS`, 0 for no cap). Measured on four
diagram calls running side by side, a diagram took 66 s with unlimited reasoning,
49 s with `effort: low`, 15 s with the 800-token cap and 8 s with reasoning off.

Every call is streamed and stopped at a wall-clock limit (`LLM_CALL_TIMEOUT_S`,
default 120 s, and never past the end of the current step). A plain read timeout
can't bound it: OpenRouter keeps a slow request alive with periodic bytes. A free
model that misses the limit hands over to the next model in the chain. If analysis
attempts keep dying without recording a failure, the job is failed after three
tries rather than retried forever. Every pipeline call
is a single turn, so there are no `reasoning_details` to pass back. A free host that
cannot enforce the schema answers 404 under `require_parameters`; that call falls
back to prompted JSON on the same model. If the free endpoint is withdrawn, the call
Expand Down
31 changes: 29 additions & 2 deletions arcvisual/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,28 @@ class LongContext:
timeout_s: float = 300.0
#: Sent as ``reasoning_effort`` when set; empty omits the parameter.
reasoning_effort: str = ""
#: OpenRouter only: send ``reasoning: {"enabled": true}``. A reasoning model plans
#: the layout of a diagram before writing it, which is the hard part of the job.
#: OpenRouter only: send ``reasoning: {"enabled": true}`` on CODEGEN calls. A
#: reasoning model plans the layout of a diagram before writing it, which is the
#: hard part of the job.
reasoning: bool = False
#: Also reason during ANALYZE. Off by default: measured on the free Nemotron
#: endpoint (~86 tokens/s), a 67k-character analysis took 112s with reasoning
#: (7,272 reasoning tokens) and 30s without — and the real one, with a schema and
#: up to 40 concepts, ran past Vercel's 300s function limit every time.
reasoning_analyze: bool = False
#: Ceiling on reasoning tokens per call (OpenRouter's `reasoning.max_tokens`); 0
#: lets the model reason as long as it likes. Measured on the free Nemotron
#: endpoint, four diagram calls side by side: unbounded 66s (2,923 reasoning
#: tokens), `effort: low` 49s, capped at 800 15s, off 8s. The cap keeps the model
#: planning the layout and makes a diagram about four times faster.
reasoning_max_tokens: int = 800
#: Wall-clock ceiling on one model call, in seconds. A read timeout cannot bound
#: it: OpenRouter keeps a slow non-streaming request alive with periodic bytes, so
#: a call outlived the serverless function and was killed instead of failing.
call_timeout_s: float = 120.0
#: Concepts to ask ANALYZE for. Bounds the reply, and with it the call's duration;
#: twelve covers the twelve-scene cap.
analysis_item_budget: int = 12
rate_in: float | None = None
rate_out: float | None = None

Expand Down Expand Up @@ -495,6 +514,14 @@ def long_context_from_env(preset: str, env=os.environ.get) -> LongContext:
timeout_s=float(env("LLM_TIMEOUT_S") or 300),
reasoning_effort=env("LLM_REASONING_EFFORT", "") or "",
reasoning=_flag(env("LLM_REASONING"), base.reasoning),
reasoning_analyze=_flag(env("LLM_REASONING_ANALYZE"), False),
reasoning_max_tokens=int(
env("LLM_REASONING_MAX_TOKENS") or LongContext.reasoning_max_tokens
),
call_timeout_s=float(env("LLM_CALL_TIMEOUT_S") or LongContext.call_timeout_s),
analysis_item_budget=int(
env("LLM_ANALYSIS_ITEMS") or LongContext.analysis_item_budget
),
rate_in=_opt_float(env("LLM_RATE_IN")),
rate_out=_opt_float(env("LLM_RATE_OUT")),
)
Expand Down
158 changes: 154 additions & 4 deletions arcvisual/providers/longcontext_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@

from __future__ import annotations

import json
import logging
import re
import threading
import time
from typing import Any

from pydantic import BaseModel
Expand All @@ -38,6 +41,7 @@
ModelUnavailable,
ProviderError,
ProviderNotConfigured,
RetryableProviderError,
StructuredResult,
Task,
TextBlock,
Expand All @@ -55,6 +59,9 @@
#: Model ids the server reported as gone, per process — shared across scene lanes.
_UNAVAILABLE: set[str] = set()

#: Below this many seconds left there is no point starting a call: it cannot finish.
_MIN_CALL_S = 10.0


class LongContextProvider(OpenAICompatProvider):
name = "longcontext"
Expand Down Expand Up @@ -82,6 +89,10 @@ def __init__(
)
self._cfg = cfg
self._http = client
#: time.monotonic() instant no call may run past; None = only call_timeout_s.
self._deadline: float | None = None
#: The task of the call in flight, per thread (scene lanes share a provider).
self._local = threading.local()
# Reports read "openrouter" or "gemini", not a generic label: a cost anomaly
# is investigated per host.
self.name = cfg.preset if cfg.preset in LONG_CONTEXT_PRESETS else "longcontext"
Expand Down Expand Up @@ -116,16 +127,136 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]:
if self._cfg.preset != "openrouter":
return {}
extra: dict[str, Any] = {}
if self._cfg.reasoning:
if self._reasons():
# Every call here is a single turn, so there is no `reasoning_details` to
# pass back: the model reasons, answers, and the next call starts fresh.
extra["reasoning"] = {"enabled": True}
cap = self._cfg.reasoning_max_tokens
extra["reasoning"] = {"max_tokens": cap} if cap > 0 else {"enabled": True}
if response_format is not None:
# Route only to upstream hosts that honour `response_format`. Without it
# OpenRouter may pick one that silently ignores the schema.
extra["provider"] = {"require_parameters": True}
return extra

def _reasons(self) -> bool:
"""Reason on this call? Diagrams yes; analysis only when asked for."""
if not self._cfg.reasoning:
return False
task = getattr(self._local, "task", None)
return task is not Task.CLASSIFY or self._cfg.reasoning_analyze

def set_deadline(self, deadline: float | None) -> None:
"""No model call may run past this ``time.monotonic()`` instant.

The stepped deployment calls this with the end of its step: a call still
running when the platform kills the function never reaches an error handler,
so the job re-runs the same doomed call on every step, forever.
"""
self._deadline = deadline

def _call_budget(self) -> float:
budget = self._cfg.call_timeout_s
if self._deadline is not None:
budget = min(budget, self._deadline - time.monotonic())
return budget

def _post(self, payload: dict[str, Any]) -> Any:
"""Stream the reply and stop at a wall-clock budget.

Non-streaming is unboundable here: OpenRouter answers 200 at once and keeps
the connection alive with periodic bytes until the model finishes, so the
HTTP read timeout never fires. Streaming yields a line at a time, and the
clock is checked on each one.
"""
model = payload.get("model", "")
budget = self._call_budget()
if budget < _MIN_CALL_S:
# Not retryable within this step: a retry would start with even less.
raise ProviderError(
f"{self.name}: only {max(budget, 0):.0f}s left in this step, too "
"little for another model call; the next step continues"
)
client = self._client()
if not hasattr(client, "stream"):
return client.post("/chat/completions", json=payload)
body: dict[str, Any] = {**payload, "stream": True}
if self._cfg.preset == "openrouter":
# Usage on a stream is opt-in there, and without it a call is billed as
# zero tokens: the job's dollar ceiling would never trip. Other hosts
# (Mistral) reject unknown request fields, so this is not sent to them.
body["stream_options"] = {"include_usage": True}
with client.stream("POST", "/chat/completions", json=body) as response:
if response.status_code != 200:
response.read()
return response
# The elapsed check below runs between lines, so it cannot end a stream
# that has gone silent: one blocked read would wait out the HTTP read
# timeout (300s) — past the function's own limit. The watchdog closes
# the stream at the budget, which unblocks that read.
expired = threading.Event()

def _expire() -> None:
expired.set()
response.close()

watchdog = threading.Timer(budget, _expire)
watchdog.daemon = True
watchdog.start()
try:
return self._read_stream(response, model, budget, expired)
finally:
watchdog.cancel()

def _read_stream(
self, response: Any, model: str, budget: float, expired: threading.Event
) -> _Reply:
content: list[str] = []
finish = None
usage: dict[str, Any] | None = None
try:
for line in response.iter_lines():
if expired.is_set():
self._too_slow(model, budget)
if not line.startswith("data:"):
continue # SSE comments are OpenRouter's keep-alives
data = line[5:].strip()
if data == "[DONE]":
break
chunk = json.loads(data)
if "error" in chunk:
error = chunk["error"] or {}
code = error.get("code")
return _Reply(code if isinstance(code, int) else 502, chunk)
usage = chunk.get("usage") or usage
for choice in chunk.get("choices") or []:
delta = choice.get("delta") or {}
if delta.get("content"):
content.append(delta["content"])
finish = choice.get("finish_reason") or finish
except ProviderError:
raise
except Exception:
if expired.is_set():
# The watchdog closed the stream mid-read.
self._too_slow(model, budget)
raise
if expired.is_set():
self._too_slow(model, budget)
message = {"content": "".join(content) if content else None}
return _Reply(
200,
{"choices": [{"message": message, "finish_reason": finish}], "usage": usage},
)

def _too_slow(self, model: str, budget: float) -> None:
if model.endswith(":free"):
# A free endpoint this slow now is no faster on the next attempt; the
# paid models behind it in the chain are the way to finish in time.
raise ModelUnavailable(model, f"no complete answer within {budget:.0f}s")
raise RetryableProviderError(
f"{self.name}: {model} gave no complete answer within {budget:.0f}s"
)

def _model_exhausted(self, model: str, body: str) -> None:
# OpenRouter caps ':free' models per day ("Rate limit exceeded:
# free-models-per-day", ~50 requests without credits). Retrying cannot clear
Expand Down Expand Up @@ -160,6 +291,7 @@ def _structured_with(
max_tokens: int,
max_attempts: int,
) -> StructuredResult:
self._local.task = task
budget = self._budget(max_tokens, model, task.value)
schema_key = (model, output_model.__name__, _schema_digest(output_model))
first: StructuredResult | None = None
Expand Down Expand Up @@ -223,7 +355,7 @@ def capabilities(self) -> Capabilities:
vision=False,
cost_attributed=attributed,
prompt_char_budget=self._cfg.prompt_char_budget,
analysis_item_budget=None,
analysis_item_budget=self._cfg.analysis_item_budget or None,
analysis_passes=1,
note=(
f"{self.model_for(Task.CLASSIFY)} for analyze / "
Expand All @@ -235,7 +367,12 @@ def capabilities(self) -> Capabilities:
if self._cfg.json_schema
else "JSON prompted and validated client-side. "
)
+ ("Reasoning enabled. " if self._cfg.reasoning else "")
+ (
"Reasoning enabled for diagrams"
+ (" and analysis. " if self._cfg.reasoning_analyze else ". ")
if self._cfg.reasoning
else ""
)
+ (preset.note + " " if preset and preset.note else "")
+ (
"Cost attributed from LLM_RATE_IN/OUT."
Expand Down Expand Up @@ -283,3 +420,16 @@ def _is_schema_refusal(exc: ProviderError) -> bool:
return any(f"returned {code}" in text for code in (400, 422)) or (
"invalid JSON schema" in text
)


class _Reply:
"""A response assembled from a stream, shaped like the httpx one `_chat` reads."""

def __init__(self, status_code: int, body: dict[str, Any]) -> None:
self.status_code = status_code
self._body = body
self.text = json.dumps(body)
self.headers: dict[str, str] = {}

def json(self) -> dict[str, Any]:
return self._body
13 changes: 12 additions & 1 deletion arcvisual/providers/openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]:
"""Host-specific request fields, merged into every chat payload."""
return {}

def _post(self, payload: dict[str, Any]) -> Any:
"""Send one chat request and return a response with ``status_code``,
``headers``, ``text`` and ``json()``. Plain, unbounded POST by default."""
return self._client().post("/chat/completions", json=payload)

def _model_exhausted(self, model: str, body: str) -> None:
"""Raise :class:`ModelUnavailable` if a 429 body means `model` is spent for
the day, so the next configured model is tried. No-op by default."""
Expand Down Expand Up @@ -363,7 +368,13 @@ def _chat(
if meter is not None:
reserved = meter.acquire(max_tokens + prompt_tokens)
try:
response = self._client().post("/chat/completions", json=payload)
response = self._post(payload)
except ProviderError:
# Already a verdict (out of time, model unavailable): pass it on as is,
# or the fallback chain would see a generic retryable failure instead.
if meter is not None:
meter.settle(reserved, 0)
raise
except Exception as exc:
if meter is not None:
meter.settle(reserved, 0) # nothing was spent; give it all back
Expand Down
41 changes: 35 additions & 6 deletions arcvisual/render/stepper.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ def advance(
try:
if provider is None:
provider = _select_provider()
set_deadline = getattr(provider, "set_deadline", None)
if set_deadline is not None:
# Model calls may run into the grace period a started scene gets, and no
# further: past it the platform kills the function mid-call, and a killed
# call never reaches the error handling that would record it.
set_deadline(deadline + ATTEMPT_GRACE_S)
while time.monotonic() < deadline:
with sf() as session:
job = session.get(Job, job_id)
Expand Down Expand Up @@ -235,12 +241,35 @@ def _step_analyze(sf, job_id, provider, deadline: float | None = None) -> bool:
job = session.get(Job, job_id)
sb = Storyboard.model_validate(job.storyboard)
attempts = int((job.stage_progress or {}).get("analyze_attempts") or 0) + 1
job.stage_progress = {
**(job.stage_progress or {}),
"stage": "analyzing",
"analyze_attempts": attempts,
}
session.commit()
if attempts <= MAX_ANALYZE_ATTEMPTS:
job.stage_progress = {
**(job.stage_progress or {}),
"stage": "analyzing",
"analyze_attempts": attempts,
}
session.commit()

if attempts > MAX_ANALYZE_ATTEMPTS:
# Every earlier attempt was counted on entry, yet none was failed on its way
# out — so each one died with its function, killed by the platform mid-call.
# Retrying would die the same way, forever: this is how a job sat in
# "analyzing" for 83 minutes.
_fail(
sf,
job_id,
{
"code": "analyze_timeout",
"message": (
f"{attempts - 1} analyze attempts ended without finishing; each "
"ran past the platform's function time limit"
),
"user_facing": (
"Reading this paper took longer than we are allowed to run. This "
"is on us, not the paper — please try again later."
),
},
)
return False

before = sb.model_copy(deep=True) if cfg.strict_ownership else None
t0 = time.perf_counter()
Expand Down
Loading
Loading