From 159d52d1b98e2dcf55cdfb3f216e66efa2e3ae29 Mon Sep 17 00:00:00 2001 From: Tom Brandenburg Date: Sun, 22 Nov 2026 14:22:15 +0100 Subject: [PATCH] feat(agent): route visualization through OpenRouter's Jev for shared server keys JEV_PROVIDER=openrouter selects OpenRouter's Decisions API with OPENROUTER_API_KEY and typesafe/jev-1.14 by default. TypeSafe remains the default; visitor keys always use TypeSafe; an unsupported value fails at startup with no fallback. Closes #147 --- .env.example | 7 ++- apps/agent/main.py | 3 +- apps/agent/src/credentials.py | 5 +- apps/agent/src/visualization_router.py | 32 +++++++++++-- apps/agent/tests/test_jev_provider.py | 66 ++++++++++++++++++++++++++ docs/deployment.md | 2 + docs/visualization-routing.md | 4 +- 7 files changed, 109 insertions(+), 10 deletions(-) create mode 100644 apps/agent/tests/test_jev_provider.py diff --git a/.env.example b/.env.example index 29bbc80c..495a292b 100644 --- a/.env.example +++ b/.env.example @@ -10,8 +10,13 @@ OPENAI_API_KEY= LLM_MODEL=chat-latest # Jev selects the renderer and visualization before each new user turn. +# JEV_PROVIDER=typesafe (default) uses TYPESAFE_API_KEY and jev-latest. +# JEV_PROVIDER=openrouter uses OPENROUTER_API_KEY and typesafe/jev-1.14. +JEV_PROVIDER=typesafe TYPESAFE_API_KEY= -JEV_MODEL=jev-latest +# OPENROUTER_API_KEY= +# JEV_MODEL overrides the provider's default model for shared-server requests. +# JEV_MODEL=jev-latest # Frontend settings: place these in apps/app/.env.local. # LANGGRAPH_DEPLOYMENT_URL defaults to http://localhost:8123. diff --git a/apps/agent/main.py b/apps/agent/main.py index 9fec803e..780fb733 100644 --- a/apps/agent/main.py +++ b/apps/agent/main.py @@ -22,7 +22,7 @@ current_credentials, validate_credentials, ) -from src.visualization_router import JevVisualizationMiddleware +from src.visualization_router import JevVisualizationMiddleware, jev_provider from src.skill_backend import SKILL_SOURCES, build_agent_backend from src.query import query_data from src.todos import AgentState, todo_tools @@ -32,6 +32,7 @@ from src.prompt import SYSTEM_PROMPT load_dotenv() +jev_provider() # fail at startup on an unsupported JEV_PROVIDER, like LLM_MODEL agent = create_deep_agent( model=CredentialScopedModel(fallback=build_model(allow_unconfigured=True)), diff --git a/apps/agent/src/credentials.py b/apps/agent/src/credentials.py index ea8cac90..d5b77adc 100644 --- a/apps/agent/src/credentials.py +++ b/apps/agent/src/credentials.py @@ -48,7 +48,10 @@ def parse_credentials(headers): def server_credentials_available(): model = os.environ.get('LLM_MODEL', 'chat-latest').strip() key = 'ANTHROPIC_API_KEY' if model.startswith('claude-') else 'OPENAI_API_KEY' - return bool(os.environ.get(key, '').strip() and os.environ.get('TYPESAFE_API_KEY', '').strip()) + from src.visualization_router import JEV_PROVIDERS, jev_provider + + jev_key = JEV_PROVIDERS[jev_provider()][0] + return bool(os.environ.get(key, '').strip() and os.environ.get(jev_key, '').strip()) class CredentialsMiddleware: diff --git a/apps/agent/src/visualization_router.py b/apps/agent/src/visualization_router.py index 928556b7..4c8fd4b8 100644 --- a/apps/agent/src/visualization_router.py +++ b/apps/agent/src/visualization_router.py @@ -12,6 +12,11 @@ from pydantic import BaseModel, Field, ValidationError JEV_URL = "https://api.typesafe.ai/v1/systemone" +OPENROUTER_JEV_URL = "https://openrouter.ai/api/alpha/decisions" +JEV_PROVIDERS = { + "typesafe": ("TYPESAFE_API_KEY", JEV_URL, "jev-latest"), + "openrouter": ("OPENROUTER_API_KEY", OPENROUTER_JEV_URL, "typesafe/jev-1.14"), +} VISUALIZATIONS = { "text": "Direct facts, prose, writing, code, conversation, or a clarification; no visual needed.", "table": "Basic table: exact values, records, simple side-by-side comparison; no custom interaction.", @@ -113,19 +118,36 @@ def routing_input(state): return turn, context +def jev_provider(): + from src.credentials import current_credentials + + # Visitor keys are TypeSafe keys; JEV_PROVIDER only selects shared-server routing. + if current_credentials.get(): + return "typesafe" + provider = os.environ.get("JEV_PROVIDER", "typesafe").strip() + if provider not in JEV_PROVIDERS: + raise ValueError("JEV_PROVIDER must be typesafe or openrouter.") + return provider + + +def jev_url(): + return JEV_PROVIDERS[jev_provider()][1] + + def request_options(context): from src.credentials import current_credentials credentials = current_credentials.get() - key = credentials.jev if credentials else os.environ.get("TYPESAFE_API_KEY", "").strip() + key_name, _, default_model = JEV_PROVIDERS[jev_provider()] + key = credentials.jev if credentials else os.environ.get(key_name, "").strip() if not key: raise ValueError( - "TYPESAFE_API_KEY is required for Jev visualization routing. Configure it and restart the agent." + f"{key_name} is required for Jev visualization routing. Configure it and restart the agent." ) return { "headers": {"Authorization": f"Bearer {key}"}, "json": { - "model": "jev-latest" if credentials else os.environ.get("JEV_MODEL", "jev-latest"), + "model": default_model if credentials else os.environ.get("JEV_MODEL", default_model), "state": {"conversation": context}, "questions": { "visualization": { @@ -159,7 +181,7 @@ def provider_trust_env(): def route(context): try: with httpx.Client(timeout=15, trust_env=provider_trust_env()) as client: - return parse_response(client.post(JEV_URL, **request_options(context))) + return parse_response(client.post(jev_url(), **request_options(context))) except httpx.HTTPError: raise ValueError( "Jev visualization routing is unavailable or timed out. Please retry." @@ -170,7 +192,7 @@ async def aroute(context): try: async with httpx.AsyncClient(timeout=15, trust_env=provider_trust_env()) as client: return parse_response( - await client.post(JEV_URL, **request_options(context)) + await client.post(jev_url(), **request_options(context)) ) except httpx.HTTPError: raise ValueError( diff --git a/apps/agent/tests/test_jev_provider.py b/apps/agent/tests/test_jev_provider.py new file mode 100644 index 00000000..16dfc388 --- /dev/null +++ b/apps/agent/tests/test_jev_provider.py @@ -0,0 +1,66 @@ +import pytest + +from src.credentials import Credentials, current_credentials, server_credentials_available +from src.visualization_router import jev_url, request_options + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch): + for name in ("JEV_PROVIDER", "JEV_MODEL", "TYPESAFE_API_KEY", "OPENROUTER_API_KEY", "OPENAI_API_KEY", "LLM_MODEL"): + monkeypatch.delenv(name, raising=False) + + +def test_typesafe_is_the_default(monkeypatch): + monkeypatch.setenv("TYPESAFE_API_KEY", "ts-secret") + options = request_options([]) + assert jev_url() == "https://api.typesafe.ai/v1/systemone" + assert options["json"]["model"] == "jev-latest" + assert options["headers"]["Authorization"] == "Bearer ts-secret" + + +def test_openrouter_uses_its_endpoint_key_and_model(monkeypatch): + monkeypatch.setenv("JEV_PROVIDER", "openrouter") + monkeypatch.setenv("OPENROUTER_API_KEY", "or-secret") + monkeypatch.setenv("TYPESAFE_API_KEY", "ts-secret") + options = request_options([]) + assert jev_url() == "https://openrouter.ai/api/alpha/decisions" + assert options["json"]["model"] == "typesafe/jev-1.14" + assert options["headers"]["Authorization"] == "Bearer or-secret" + monkeypatch.setenv("JEV_MODEL", "typesafe/jev-1.13") + assert request_options([])["json"]["model"] == "typesafe/jev-1.13" + + +def test_openrouter_without_its_key_names_the_missing_variable(monkeypatch): + monkeypatch.setenv("JEV_PROVIDER", "openrouter") + monkeypatch.setenv("TYPESAFE_API_KEY", "ts-secret") + with pytest.raises(ValueError, match="OPENROUTER_API_KEY"): + request_options([]) + + +def test_unknown_provider_is_rejected_without_fallback(monkeypatch): + monkeypatch.setenv("JEV_PROVIDER", "other") + monkeypatch.setenv("TYPESAFE_API_KEY", "ts-secret") + with pytest.raises(ValueError, match="JEV_PROVIDER"): + jev_url() + + +def test_visitor_keys_stay_on_typesafe_even_when_server_uses_openrouter(monkeypatch): + monkeypatch.setenv("JEV_PROVIDER", "openrouter") + monkeypatch.setenv("JEV_MODEL", "server-model") + token = current_credentials.set(Credentials("visitor-openai", "visitor-jev")) + try: + assert jev_url() == "https://api.typesafe.ai/v1/systemone" + assert request_options([])["json"]["model"] == "jev-latest" + finally: + current_credentials.reset(token) + + +def test_server_credentials_follow_the_selected_provider(monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "openai") + monkeypatch.setenv("OPENROUTER_API_KEY", "or") + assert not server_credentials_available() + monkeypatch.setenv("JEV_PROVIDER", "openrouter") + assert server_credentials_available() + monkeypatch.setenv("JEV_PROVIDER", "typesafe") + monkeypatch.setenv("TYPESAFE_API_KEY", "ts") + assert server_credentials_available() diff --git a/docs/deployment.md b/docs/deployment.md index 1bbf12d8..c2019075 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -18,6 +18,8 @@ For shared credentials, the blueprint and Python factory default to `LLM_MODEL=c | `LLM_MODEL` | Agent | `claude-*` routes to Anthropic; `gpt-*` routes to OpenAI | | `ANTHROPIC_API_KEY` | Agent | Required when selecting Anthropic | | `OPENAI_API_KEY` | Agent | Required when selecting OpenAI | +| `JEV_PROVIDER` | Agent | `typesafe` (default) or `openrouter`; selects the shared-server Jev provider | +| `OPENROUTER_API_KEY` | Agent | Jev key when `JEV_PROVIDER=openrouter` | | `LANGSMITH_API_KEY` | As configured | Optional tracing configuration | | `LANGGRAPH_DEPLOYMENT_URL` | Frontend | Blueprint obtains agent host:port via `fromService`; runtime normalizes it to a URL | | `RATE_LIMIT_ENABLED` | Frontend | Defaults to `false` in blueprint | diff --git a/docs/visualization-routing.md b/docs/visualization-routing.md index 77622a0f..e890024e 100644 --- a/docs/visualization-routing.md +++ b/docs/visualization-routing.md @@ -2,7 +2,7 @@ The answer model defaults to `chat-latest`, the documented API alias for the latest ChatGPT Instant model. This is a moving alias, not a pinned `gpt-6-instant` snapshot. Its available model ID was verified using the configured OpenAI account. See [OpenAI's model documentation](https://developers.openai.com/api/docs/models/chat-latest). -Jev (`jev-latest`) makes one typed presentation decision for each new user message through [TypeSafe's System One API](https://docs.typesafe.ai/introduction/quickstart). It receives up to four recent user/assistant text messages, capped at 6,000 characters each. It does not receive API keys, system instructions, raw tool outputs, or generated tool code. +Jev makes one typed presentation decision for each new user message through [TypeSafe's System One API](https://docs.typesafe.ai/introduction/quickstart) (`jev-latest`) or, for shared-server routing, [OpenRouter's Decisions API](https://openrouter.ai/docs/guides/community/jev) (`typesafe/jev-1.14`). It receives up to four recent user/assistant text messages, capped at 6,000 characters each. It does not receive API keys, system instructions, raw tool outputs, or generated tool code. | Selected visualization | Renderer | | --- | --- | @@ -17,7 +17,7 @@ The renderer is derived from Jev's validated choice, preventing contradictory re The A2UI catalog supplies a semantic HTML table with column headers, a caption, keyboard-focusable horizontal scrolling, and a required provenance label. It accepts at most 12 columns and 200 rows and rejects mismatched row widths. React renders values as text. Charts and diagrams continue to use the existing isolated sandbox. -Set `OPENAI_API_KEY`, `TYPESAFE_API_KEY`, `LLM_MODEL=chat-latest`, and optionally `JEV_MODEL=jev-latest` on the agent server. Provider secrets never belong in browser variables. Existing `claude-*` and `gpt-*` overrides remain available. Jev authentication failures, invalid choices, and timeouts fail the turn with a retryable error; there is no silent fallback claiming that Jev made a decision. Successful health checks confirm the server is running, not provider access. +Set `OPENAI_API_KEY`, `LLM_MODEL=chat-latest`, and a Jev key on the agent server: `TYPESAFE_API_KEY` by default, or `JEV_PROVIDER=openrouter` with `OPENROUTER_API_KEY`. `JEV_MODEL` optionally overrides the provider's default model. An unsupported `JEV_PROVIDER` fails at startup, and there is no fallback between providers. Visitor-supplied keys always use TypeSafe. Provider secrets never belong in browser variables. Existing `claude-*` and `gpt-*` overrides remain available. Jev authentication failures, invalid choices, and timeouts fail the turn with a retryable error; there is no silent fallback claiming that Jev made a decision. Successful health checks confirm the server is running, not provider access. Routing is a model judgment, not a guarantee of the objectively best visualization. Missing source data still requires clarification or explicit illustrative assumptions. Live provider checks and browser checks complement the deterministic routing, error-path, continuation, and A2UI rendering tests.