diff --git a/.env.example b/.env.example index 0b7244b..7a4dba6 100644 --- a/.env.example +++ b/.env.example @@ -60,7 +60,8 @@ GROQ_API_KEY= # ARCVISUAL_PROVIDER=auto, the first preset whose key is set is used (after Anthropic). # # preset key default models (comma = fallback chain) context -# openrouter OPENROUTER_API_KEY qwen/qwen3-235b-a22b-2507, deepseek-v3.2, gpt-oss-120b 131-262K +# openrouter OPENROUTER_API_KEY nvidia/nemotron-3.5-lightning:free, then qwen3-235b-2507, +# deepseek-v3.2, gpt-oss-120b (reasoning on) 131-262K # gemini GEMINI_API_KEY gemini-flash-latest (AI Studio, free tier) ~1M (budgeted 262K) # mistral MISTRAL_API_KEY mistral-medium-latest (free Experiment plan) 131K # deepseek DEEPSEEK_API_KEY deepseek-v4-flash (paid, very cheap) 131K+ @@ -84,6 +85,7 @@ 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_RATE_IN= / LLM_RATE_OUT= # USD per million tokens; empty = unattributed # Formula-chain scenes allowed per paper. Past this, transform_chain proposals are diff --git a/README.md b/README.md index 05ade58..0ddee93 100644 --- a/README.md +++ b/README.md @@ -342,7 +342,7 @@ the full section a visual comes from (12,000 chars) instead of a 1,500-char quot | Preset | Key | Default models (fallback chain) | Context | Plan | |---|---|---|---|---| -| `openrouter` | `OPENROUTER_API_KEY` | `qwen/qwen3-235b-a22b-2507`, `deepseek/deepseek-v3.2`, `openai/gpt-oss-120b` | 131K–262K | paid per token; `:free` ids rate-limited | +| `openrouter` | `OPENROUTER_API_KEY` | `nvidia/nemotron-3.5-lightning:free` (reasoning on), then `qwen/qwen3-235b-a22b-2507`, `deepseek/deepseek-v3.2`, `openai/gpt-oss-120b` | 131K–262K | Nemotron free endpoint first; paid fallbacks | | `gemini` | `GEMINI_API_KEY` | `gemini-flash-latest` | ~1M (budgeted 262K) | AI Studio free tier | | `mistral` | `MISTRAL_API_KEY` | `mistral-medium-latest`, `mistral-small-latest` | 131K | free Experiment plan | | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-v4-flash` | 131K+ | paid, very cheap | @@ -357,6 +357,13 @@ 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 +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 +moves on to the next model in the chain. + ### Operational notes, measured rather than assumed | Provider | Finding | diff --git a/arcvisual/config.py b/arcvisual/config.py index 9e6c33c..337f85e 100644 --- a/arcvisual/config.py +++ b/arcvisual/config.py @@ -344,6 +344,8 @@ class LongContextPreset: #: False sends the schema in the prompt and validates client-side instead. json_schema: bool note: str = "" + #: Ask the host to reason before answering (OpenRouter's `reasoning.enabled`). + reasoning: bool = False #: Hosts whose models take 100K-260K tokens in a single request, so ANALYZE reads the @@ -358,13 +360,23 @@ class LongContextPreset: "openrouter": LongContextPreset( base_url="https://openrouter.ai/api/v1", key_env="OPENROUTER_API_KEY", - # qwen3-235b 2507 natively serves 262,144 tokens; the fallbacks serve 131,072. - classify="qwen/qwen3-235b-a22b-2507,deepseek/deepseek-v3.2,openai/gpt-oss-120b", - codegen="qwen/qwen3-235b-a22b-2507,openai/gpt-oss-120b,deepseek/deepseek-v3.2", + # NVIDIA Nemotron 3.5 Lightning (free endpoint) leads both chains: it is the + # model chosen for drawing diagrams of concepts. A free endpoint is rate-limited + # and can be withdrawn, so the paid long-context models follow it. qwen3-235b + # 2507 natively serves 262,144 tokens; the others are budgeted at 131,072. + classify=( + "nvidia/nemotron-3.5-lightning:free,qwen/qwen3-235b-a22b-2507," + "deepseek/deepseek-v3.2,openai/gpt-oss-120b" + ), + codegen=( + "nvidia/nemotron-3.5-lightning:free,qwen/qwen3-235b-a22b-2507," + "openai/gpt-oss-120b,deepseek/deepseek-v3.2" + ), context_tokens=131072, json_schema=True, - note="One key, many hosts. Append :free to a model id for the rate-limited free " - "endpoint (about 50 requests/day); free endpoints may serve less context.", + reasoning=True, + note="One key, many hosts. ':free' ids are rate-limited (about 50 requests/" + "day) and may serve less context than the paid endpoint.", ), "gemini": LongContextPreset( base_url="https://generativelanguage.googleapis.com/v1beta/openai", @@ -441,6 +453,9 @@ 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. + reasoning: bool = False rate_in: float | None = None rate_out: float | None = None @@ -479,6 +494,7 @@ def long_context_from_env(preset: str, env=os.environ.get) -> LongContext: temperature=float(env("LLM_TEMPERATURE") or 0.2), timeout_s=float(env("LLM_TIMEOUT_S") or 300), reasoning_effort=env("LLM_REASONING_EFFORT", "") or "", + reasoning=_flag(env("LLM_REASONING"), base.reasoning), rate_in=_opt_float(env("LLM_RATE_IN")), rate_out=_opt_float(env("LLM_RATE_OUT")), ) @@ -790,6 +806,13 @@ def _long_context_preset(env=os.environ.get) -> str: return "openrouter" +def _flag(value: str | None, default: bool) -> bool: + """An on/off env var: unset or empty keeps the default, "0"/"false"/"off" is off.""" + if value is None or not value.strip(): + return default + return value.strip().lower() not in ("0", "false", "off", "no") + + def _opt_float(value: str | None) -> float | None: """None stays None. A rate we do not know must not become 0.0, or an unattributed cost would be reported as free.""" diff --git a/arcvisual/providers/longcontext_provider.py b/arcvisual/providers/longcontext_provider.py index 840ed78..01cda6f 100644 --- a/arcvisual/providers/longcontext_provider.py +++ b/arcvisual/providers/longcontext_provider.py @@ -27,6 +27,7 @@ from __future__ import annotations import logging +import re from typing import Any from pydantic import BaseModel @@ -112,11 +113,26 @@ def _reasoning_effort(self, model: str = "") -> str: return self._cfg.reasoning_effort def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: - if self._cfg.preset == "openrouter" and response_format is not None: + if self._cfg.preset != "openrouter": + return {} + extra: dict[str, Any] = {} + if self._cfg.reasoning: + # 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} + 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. - return {"provider": {"require_parameters": True}} - return {} + extra["provider"] = {"require_parameters": True} + return extra + + 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 + # that until tomorrow, and failing the call would never reach the paid models + # behind it in the chain — so the free model is reported spent instead. + if model.endswith(":free") and re.search(r"per[- ]day", body, re.IGNORECASE): + raise ModelUnavailable(model, "free-model daily quota exhausted") def supports_json_schema(self, model: str = "") -> bool: return self._cfg.json_schema @@ -170,15 +186,24 @@ def _structured_with( def send(system_text: str, user_text: str) -> tuple[str, Usage]: return self._chat(model, system_text, user_text, budget) - result = prompted_structured( - send=send, - system=system, - user=user, - output_model=output_model, - provider=self.name, - model=model, - max_attempts=max_attempts, - ) + try: + result = prompted_structured( + send=send, + system=system, + user=user, + output_model=output_model, + provider=self.name, + model=model, + max_attempts=max_attempts, + ) + except ProviderError as exc: + # Without `response_format` there is no parameter to route around, so + # OpenRouter's "No endpoints found" means the model itself has no live + # host — a withdrawn ':free' endpoint. That is the one failure where the + # next model in the chain is the right answer. + if "returned 404" in str(exc) and "No endpoints found" in str(exc): + raise ModelUnavailable(model, str(exc)[:200]) from exc + raise if first is not None: # The failed constrained attempt was still billed. result.usage = first.usage.merge(result.usage) @@ -210,6 +235,7 @@ def capabilities(self) -> Capabilities: if self._cfg.json_schema else "JSON prompted and validated client-side. " ) + + ("Reasoning enabled. " if self._cfg.reasoning else "") + (preset.note + " " if preset and preset.note else "") + ( "Cost attributed from LLM_RATE_IN/OUT." @@ -249,6 +275,11 @@ def _is_schema_refusal(exc: ProviderError) -> bool: if isinstance(exc, ModelUnavailable): return False # the id is gone; the caller moves to the next model text = str(exc) + # OpenRouter with `require_parameters` answers 404 "No endpoints found that can + # handle the requested parameters" when no host serving this model supports + # `response_format` — common on free endpoints. Prompted JSON still works there. + if "returned 404" in text and "No endpoints found" in text: + return True return any(f"returned {code}" in text for code in (400, 422)) or ( "invalid JSON schema" in text ) diff --git a/arcvisual/providers/openai_compat.py b/arcvisual/providers/openai_compat.py index 2a1bbf6..a4e5c46 100644 --- a/arcvisual/providers/openai_compat.py +++ b/arcvisual/providers/openai_compat.py @@ -110,6 +110,10 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: """Host-specific request fields, merged into every chat payload.""" return {} + 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.""" + def _token_budget(self, model: str = "") -> TokenBudget | None: """A per-minute token meter shared across this provider's callers, or None. @@ -371,6 +375,11 @@ def _chat( if meter is not None: meter.observe(response.headers) + if response.status_code == 429: + # A host may know that this 429 means the MODEL is out of quota rather + # than the moment; it raises ModelUnavailable so the chain moves on. + self._model_exhausted(model, response.text) + if response.status_code == 429 and is_daily_limit(response.text): if meter is not None: meter.penalise(response.headers) diff --git a/tests/test_longcontext.py b/tests/test_longcontext.py index 74781fa..221b5ab 100644 --- a/tests/test_longcontext.py +++ b/tests/test_longcontext.py @@ -249,3 +249,109 @@ def test_cost_is_unattributed_until_rates_are_set(reset_settings) -> None: ) assert result.usage.attributed is True assert result.usage.cost_usd == pytest.approx((100 * 1.0 + 20 * 2.0) / 1e6) + + +# --------------------------------------------------------------------------- # +# Nemotron on OpenRouter's free endpoint +# --------------------------------------------------------------------------- # + + +def test_openrouter_leads_with_nemotron_and_asks_it_to_reason(reset_settings) -> None: + http = _Http(_ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http) + assert provider.model_for(Task.CODEGEN) == "nvidia/nemotron-3.5-lightning:free" + assert provider.model_for(Task.CLASSIFY) == "nvidia/nemotron-3.5-lightning:free" + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert http.sent[0]["model"] == "nvidia/nemotron-3.5-lightning:free" + assert http.sent[0]["reasoning"] == {"enabled": True} + + +def test_reasoning_can_be_turned_off(reset_settings) -> None: + http = _Http(_ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http, LLM_REASONING="0") + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert "reasoning" not in http.sent[0] + + +def test_reasoning_is_openrouter_only(reset_settings) -> None: + from arcvisual.providers.longcontext_provider import LongContextProvider + + reset_settings(ARCVISUAL_PROVIDER="mistral", MISTRAL_API_KEY="k", LLM_REASONING="1") + http = _Http(_ok('{"answer": "ok"}')) + LongContextProvider(client=http).structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert "reasoning" not in http.sent[0] + + +NO_SCHEMA_HOST = _Resp( + 404, + '{"error":{"message":"No endpoints found that can handle the requested ' + 'parameters.","code":404}}', +) +NO_HOST_AT_ALL = _Resp( + 404, + '{"error":{"message":"No endpoints found for nvidia/nemotron-3.5-lightning:free.",' + '"code":404}}', +) + + +def test_a_free_endpoint_without_schema_support_is_prompted(reset_settings) -> None: + """require_parameters + a free host that lacks response_format = a 404, not an + answer. The schema goes in the prompt instead, on the same model.""" + http = _Http(NO_SCHEMA_HOST, _ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http) + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert result.ok and result.model == "nvidia/nemotron-3.5-lightning:free" + assert "response_format" not in http.sent[1] + assert "provider" not in http.sent[1] + + +def test_a_withdrawn_free_endpoint_falls_through_to_the_next_model( + reset_settings, +) -> None: + http = _Http(NO_SCHEMA_HOST, NO_HOST_AT_ALL, _ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http) + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" + + +FREE_DAILY_QUOTA = _Resp( + 429, + '{"error":{"message":"Rate limit exceeded: free-models-per-day. Add 10 credits ' + 'to unlock 1000 free model requests per day","code":429}}', +) + + +def test_a_spent_free_quota_falls_through_to_the_paid_model(reset_settings) -> None: + """Retrying a daily cap cannot succeed until tomorrow; the paid models behind the + free one are the only way the paper still gets explained today.""" + http = _Http(FREE_DAILY_QUOTA, _ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http) + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" + # Remembered for the rest of the process: the next call skips the spent model. + assert provider.model_for(Task.CLASSIFY) == "qwen/qwen3-235b-a22b-2507" + + +def test_a_paid_models_daily_limit_is_not_mistaken_for_a_free_quota( + reset_settings, +) -> None: + from arcvisual.providers.base import ProviderError + + http = _Http(_Resp(429, '{"error":{"message":"tokens per day (TPD): Limit 1"}}')) + provider = _provider(reset_settings, http, LLM_MODEL_CODEGEN="paid/model") + with pytest.raises(ProviderError, match="daily token quota"): + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + )