Skip to content
Open
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: 6 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion apps/agent/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)),
Expand Down
5 changes: 4 additions & 1 deletion apps/agent/src/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
32 changes: 27 additions & 5 deletions apps/agent/src/visualization_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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."
Expand All @@ -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(
Expand Down
66 changes: 66 additions & 0 deletions apps/agent/tests/test_jev_provider.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 2 additions & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 2 additions & 2 deletions docs/visualization-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --- | --- |
Expand All @@ -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.

Expand Down