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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,11 @@ make dev

Open the [app](http://localhost:3000). The [agent health endpoint](http://localhost:8123/health) confirms the agent service is running. See [Getting started](docs/getting-started.md) for configuration and verification.

The default model is `chat-latest`, OpenAI’s documented alias for the latest ChatGPT Instant model, requiring `OPENAI_API_KEY`. Jev (`jev-latest`, requiring `TYPESAFE_API_KEY`) selects the renderer and visualization for each user turn. Basic tables use A2UI; charts, diagrams, calculators, and maps use Open Generative UI. Provider failures are surfaced instead of silently substituting another router or model. See [Visualization routing](docs/visualization-routing.md).
The default model is `chat-latest`, OpenAI’s documented alias for the latest ChatGPT Instant model, requiring `OPENAI_API_KEY`. Jev selects the renderer and visualization for each user turn via TypeSafe or OpenRouter. Basic tables use A2UI; charts, diagrams, calculators, and maps use Open Generative UI. Provider failures are surfaced instead of silently substituting another router or model. See [Visualization routing](docs/visualization-routing.md).

## Use your own API keys

The chat asks for both keys before sending your first message or example prompt and keeps your draft while you set them up. Open **API keys** in the chat header, enter an OpenAI key and a Jev key, then choose **Test connection** and **Save keys**. The connection test makes a small request to each provider. Your keys use `chat-latest` for answers and `jev-latest` for visualization routing, with usage billed to your provider accounts.
The chat asks for both keys before sending your first message or example prompt and keeps your draft while you set them up. Open **API keys** in the chat header, enter an OpenAI key, select TypeSafe or OpenRouter for Jev and enter its key, then choose **Test connection** and **Save keys**. The connection test makes a small request to each provider. Your keys use `chat-latest` for answers and the selected provider's Jev model for visualization routing, with usage billed to your provider accounts.

Keys stay in browser memory until refresh or **Clear keys**; the app does not save them in browser storage. Requests send them through the application server to their respective providers. They are kept out of chat state and checkpoints, and hosted LangSmith tracing is disabled for requests using your keys. Only use this feature on a deployment whose operator you trust. Saving or clearing keys starts a new chat; **New chat** keeps your keys for the current session.

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
21 changes: 14 additions & 7 deletions apps/agent/src/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
class Credentials:
openai: str = field(repr=False)
jev: str = field(repr=False)
jev_provider: str = 'typesafe'


current_credentials: ContextVar[Credentials | None] = ContextVar('provider_credentials', default=None)
SENSITIVE_HEADERS = {b'x-openai-api-key', b'x-jev-api-key'}
SENSITIVE_HEADERS = {b'x-openai-api-key', b'x-jev-api-key', b'x-jev-provider'}


def parse_credentials(headers):
Expand All @@ -40,15 +41,21 @@ def parse_credentials(headers):
values[name] = value.decode('ascii')
if not values:
return None
if len(values) != 2:
if b'x-openai-api-key' not in values or b'x-jev-api-key' not in values:
raise ValueError('invalid_keys')
return Credentials(values[b'x-openai-api-key'], values[b'x-jev-api-key'])
provider = values.get(b'x-jev-provider', 'typesafe')
if provider not in {'typesafe', 'openrouter'}:
raise ValueError('invalid_keys')
return Credentials(values[b'x-openai-api-key'], values[b'x-jev-api-key'], provider)


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 Expand Up @@ -77,7 +84,7 @@ async def __call__(self, scope, receive, send):
def private_thread_id(thread_id):
credentials = current_credentials.get()
if credentials:
key = hashlib.sha256(json.dumps([credentials.openai, credentials.jev]).encode()).digest()
key = hashlib.sha256(json.dumps([credentials.openai, credentials.jev, credentials.jev_provider]).encode()).digest()
namespace = 'byok'
else:
key = b'open-intelligent-ui-server-threads-v1'
Expand All @@ -98,7 +105,7 @@ async def run(self, input):

async def validate_credentials(credentials):
"""Exercise both APIs; never forward their response bodies or exceptions."""
from src.visualization_router import JEV_URL, request_options
from src.visualization_router import jev_url, request_options

async def check(provider, url, options):
try:
Expand All @@ -119,7 +126,7 @@ async def check(provider, url, options):
'headers': {'Authorization': f'Bearer {credentials.openai}'},
'json': {'model': 'chat-latest', 'messages': [{'role': 'user', 'content': 'Reply OK.'}], 'max_completion_tokens': 8},
}),
check('jev', JEV_URL, request_options([{'role': 'human', 'content': 'Hello'}])),
check('jev', jev_url(), request_options([{'role': 'human', 'content': 'Hello'}])),
)
finally:
current_credentials.reset(token)
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

credentials = current_credentials.get()
if credentials:
return credentials.jev_provider
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
34 changes: 34 additions & 0 deletions apps/agent/tests/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,40 @@ def test_headers_validate_without_disclosing_values():
parse_credentials([(b'x-openai-api-key', b'only')])


def test_openrouter_selection_is_explicit_and_namespaces_threads():
from src.credentials import parse_credentials, current_credentials, private_thread_id
headers = [(b'x-openai-api-key', b'o'), (b'x-jev-api-key', b'j')]
typesafe = parse_credentials(headers)
router = parse_credentials(headers + [(b'x-jev-provider', b'openrouter')])
assert typesafe.jev_provider == 'typesafe'
assert router.jev_provider == 'openrouter'
token = current_credentials.set(typesafe)
try:
first = private_thread_id('thread')
finally:
current_credentials.reset(token)
token = current_credentials.set(router)
try:
assert first != private_thread_id('thread')
finally:
current_credentials.reset(token)
with pytest.raises(ValueError):
parse_credentials(headers + [(b'x-jev-provider', b'unknown')])


def test_openrouter_routes_to_its_own_endpoint(monkeypatch):
from src.credentials import Credentials, current_credentials
from src.visualization_router import jev_url, request_options
monkeypatch.setenv('JEV_MODEL', 'server-model')
token = current_credentials.set(Credentials('openai', 'router-secret', 'openrouter'))
try:
assert jev_url() == 'https://openrouter.ai/api/alpha/decisions'
assert request_options([])['json']['model'] == 'typesafe/jev-1.14'
assert request_options([])['headers']['Authorization'] == 'Bearer router-secret'
finally:
current_credentials.reset(token)


def test_concurrent_streams_isolate_keys_and_reset_on_cancellation():
from src.credentials import CredentialsMiddleware, current_credentials
async def exercise():
Expand Down
72 changes: 72 additions & 0 deletions apps/agent/tests/test_jev_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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_provider_choice_overrides_the_server_setting(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)
token = current_credentials.set(Credentials("visitor-openai", "visitor-jev", "openrouter"))
try:
assert jev_url() == "https://openrouter.ai/api/alpha/decisions"
assert request_options([])["json"]["model"] == "typesafe/jev-1.14"
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()
12 changes: 9 additions & 3 deletions apps/app/src/components/chat/provider-keys-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function ProviderKeysDialog({ onClose, disabled = false }: { onClose: ()
const request = useRef<AbortController | null>(null);
const [openai, setOpenai] = useState("");
const [jev, setJev] = useState("");
const [provider, setProvider] = useState<"typesafe" | "openrouter">("typesafe");
const [pending, setPending] = useState(false);
const [validated, setValidated] = useState(false);
const [error, setError] = useState<string | null>(null);
Expand Down Expand Up @@ -38,7 +39,7 @@ export function ProviderKeysDialog({ onClose, disabled = false }: { onClose: ()
try {
const response = await fetch("/api/provider-keys", {
method: "POST",
headers: { "x-openai-api-key": openai.trim(), "x-jev-api-key": jev.trim() },
headers: { "x-openai-api-key": openai.trim(), "x-jev-api-key": jev.trim(), ...(provider === "openrouter" ? { "x-jev-provider": provider } : {}) },
signal: controller.signal,
cache: "no-store",
});
Expand Down Expand Up @@ -66,15 +67,20 @@ export function ProviderKeysDialog({ onClose, disabled = false }: { onClose: ()
<form onSubmit={(event) => { event.preventDefault(); void testConnection(); }}>
<label htmlFor="provider-openai-key">OpenAI API key</label>
<input id="provider-openai-key" type="password" maxLength={4096} autoComplete="off" spellCheck={false} autoCapitalize="none" value={openai} onChange={(event) => edit(setOpenai, event.target.value)} disabled={pending || disabled} />
<label htmlFor="provider-jev-key">Jev API key</label>
<label htmlFor="provider-jev-provider">Jev provider</label>
<select id="provider-jev-provider" value={provider} disabled={pending || disabled} onChange={(event) => { setProvider(event.target.value === "openrouter" ? "openrouter" : "typesafe"); setValidated(false); setError(null); }}>
<option value="typesafe">TypeSafe</option>
<option value="openrouter">OpenRouter</option>
</select>
<label htmlFor="provider-jev-key">{provider === "openrouter" ? "OpenRouter API key" : "Jev API key"}</label>
<input id="provider-jev-key" type="password" maxLength={4096} autoComplete="off" spellCheck={false} autoCapitalize="none" value={jev} onChange={(event) => edit(setJev, event.target.value)} disabled={pending || disabled} />
{error && <p role="alert">{error}</p>}
<p role="status" aria-live="polite">{pending ? "Checking both providers…" : validated ? "Both keys work. Save to start a new chat." : hasKeys ? "Your own keys are active for this session." : "Both keys are required to start chatting."}</p>
<div className="provider-keys-actions">
{hasKeys && <button type="button" disabled={pending || disabled} onClick={() => { clear(); onClose(); }}>Clear keys</button>}
<button type="button" onClick={onClose}>Cancel</button>
<button type="submit" disabled={pending || disabled || !openai.trim() || !jev.trim()}>Test connection</button>
<button type="button" className="provider-keys-save" disabled={!validated || pending || disabled} onClick={() => { save({ openai: openai.trim(), jev: jev.trim() }); onClose(); }}>Save keys</button>
<button type="button" className="provider-keys-save" disabled={!validated || pending || disabled} onClick={() => { save({ openai: openai.trim(), jev: jev.trim(), ...(provider === "openrouter" ? { jevProvider: provider } : {}) }); onClose(); }}>Save keys</button>
</div>
</form>
</dialog>
Expand Down
2 changes: 1 addition & 1 deletion apps/app/src/components/chat/provider-keys.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
.provider-keys-dialog h2 { margin: 0 0 12px; font-size: 20px; font-weight: 600; }
.provider-keys-dialog p { margin: 12px 0; font-size: 13px; line-height: 1.6; }
.provider-keys-dialog label { display: block; margin: 16px 0 6px; font-size: 13px; font-weight: 500; }
.provider-keys-dialog input { width: 100%; min-width: 0; border: 1px solid var(--border-default); border-radius: 8px; padding: 10px; background: var(--surface-primary); font-size: 16px; }
.provider-keys-dialog input, .provider-keys-dialog select { width: 100%; min-width: 0; border: 1px solid var(--border-default); border-radius: 8px; padding: 10px; background: var(--surface-primary); font-size: 16px; }
.provider-keys-actions { display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-top: 20px; }
.provider-keys-actions button { padding: 10px 12px; border: 1px solid var(--border-default); border-radius: 8px; font-size: 12px; cursor: pointer; }
.provider-keys-actions .provider-keys-save { background: var(--text-primary); color: var(--surface-primary); }
Expand Down
Loading