byok-settings.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>API Key Settings — Tasmanian Planning Scheme Assistant</title>
  7. <meta name="description" content="Configure your own LLM API key to use Claude, GPT-4 or Grok with the Tasmanian Planning Scheme Assistant.">
  8. <link rel="canonical" href="https://tasplanning.report/byok-settings">
  9. <meta name="robots" content="noindex,nofollow">
  10. <link rel="preconnect" href="https://fonts.googleapis.com">
  11. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  12. <link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;1,9..40,300&display=swap" rel="stylesheet">
  13. <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  14. <link rel="icon" href="/favicon.ico">
  15. <link rel="stylesheet" href="/css/design-tokens.css">
  16. <style>
  17. *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  18. body {
  19. font-family: var(--sans); background: var(--bg); color: var(--text-primary);
  20. font-size: 15px; line-height: 1.65; -webkit-font-smoothing: antialiased;
  21. min-height: 100vh;
  22. }
  23. ::selection { background: var(--accent); color: #0b0f0e; }
  24. /* Nav */
  25. .site-nav {
  26. background: rgba(11,15,14,0.95); backdrop-filter: blur(12px);
  27. border-bottom: 1px solid var(--border);
  28. position: sticky; top: 0; z-index: 100;
  29. }
  30. .nav-inner {
  31. max-width: 900px; margin: 0 auto; padding: 0 24px;
  32. display: flex; align-items: center; justify-content: space-between; height: 54px;
  33. }
  34. .nav-brand {
  35. display: flex; align-items: center; gap: 9px;
  36. font-size: 0.85rem; font-weight: 500; color: var(--text-primary); text-decoration: none;
  37. }
  38. .nav-back {
  39. font-size: 0.8rem; color: var(--text-secondary); text-decoration: none;
  40. display: flex; align-items: center; gap: 5px;
  41. transition: color var(--transition);
  42. }
  43. .nav-back:hover { color: var(--accent); }
  44. /* Page */
  45. .page { max-width: 720px; margin: 0 auto; padding: 40px 24px 80px; }
  46. .page-header { margin-bottom: 32px; }
  47. .page-header h1 { font-family: var(--serif); font-size: 2rem; font-weight: 400; margin-bottom: 8px; }
  48. .page-header h1 em { font-style: italic; color: var(--accent); }
  49. .page-header p { color: var(--text-secondary); font-size: 0.9rem; max-width: 520px; }
  50. /* Security notice */
  51. .security-notice {
  52. background: var(--warn-dim); border: 1px solid rgba(240,192,96,0.25);
  53. border-radius: var(--radius); padding: 14px 18px;
  54. display: flex; gap: 12px; align-items: flex-start; margin-bottom: 28px;
  55. }
  56. .security-notice i { color: var(--warn); font-size: 1.1rem; flex-shrink: 0; margin-top: 2px; }
  57. .security-notice p { font-size: 0.82rem; color: var(--text-secondary); line-height: 1.6; }
  58. .security-notice strong { color: var(--warn); }
  59. /* Provider cards */
  60. .provider-grid { display: flex; flex-direction: column; gap: 16px; }
  61. .provider-card {
  62. background: var(--bg-card); border: 1px solid var(--border);
  63. border-radius: var(--radius-lg); overflow: hidden;
  64. transition: border-color var(--transition);
  65. }
  66. .provider-card.has-key { border-color: rgba(45,220,138,0.3); }
  67. .provider-card.active-provider { border-color: var(--accent); }
  68. .provider-header {
  69. padding: 16px 20px; display: flex; align-items: center; gap: 14px;
  70. cursor: pointer; user-select: none;
  71. }
  72. .provider-logo {
  73. width: 36px; height: 36px; border-radius: 8px;
  74. display: flex; align-items: center; justify-content: center;
  75. font-size: 1.1rem; flex-shrink: 0;
  76. }
  77. .provider-info { flex: 1; }
  78. .provider-name { font-size: 0.95rem; font-weight: 500; margin-bottom: 2px; }
  79. .provider-desc { font-size: 0.75rem; color: var(--text-muted); }
  80. .provider-status {
  81. display: flex; align-items: center; gap: 6px;
  82. font-size: 0.72rem; font-weight: 500;
  83. }
  84. .status-pill {
  85. padding: 3px 10px; border-radius: 999px; font-size: 0.7rem; font-weight: 500;
  86. }
  87. .status-pill.configured {
  88. background: var(--accent-dim); color: var(--accent);
  89. border: 1px solid rgba(45,220,138,0.25);
  90. }
  91. .status-pill.not-set {
  92. background: var(--bg-2); color: var(--text-muted);
  93. border: 1px solid var(--border);
  94. }
  95. .status-pill.active {
  96. background: var(--accent); color: #0b0f0e;
  97. }
  98. .expand-icon { color: var(--text-muted); transition: transform var(--transition); }
  99. .provider-card.expanded .expand-icon { transform: rotate(180deg); }
  100. .provider-body {
  101. display: none; padding: 0 20px 20px; border-top: 1px solid var(--border);
  102. }
  103. .provider-card.expanded .provider-body { display: block; }
  104. /* Form elements */
  105. .field-group { margin-top: 16px; }
  106. .field-label {
  107. display: block; font-size: 0.7rem; font-weight: 500;
  108. letter-spacing: 0.09em; text-transform: uppercase;
  109. color: var(--text-muted); margin-bottom: 6px;
  110. }
  111. .key-input-wrap { position: relative; }
  112. .key-input {
  113. width: 100%; background: var(--bg-2); border: 1px solid var(--border);
  114. border-radius: var(--radius-sm); padding: 10px 44px 10px 12px;
  115. color: var(--text-primary); font-family: var(--mono); font-size: 0.8rem;
  116. outline: none; transition: border-color var(--transition);
  117. }
  118. .key-input:focus { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-dim); }
  119. .key-input::placeholder { color: var(--text-muted); font-family: var(--sans); }
  120. .key-toggle {
  121. position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
  122. background: none; border: none; color: var(--text-muted); cursor: pointer;
  123. font-size: 0.9rem; padding: 4px;
  124. transition: color var(--transition);
  125. }
  126. .key-toggle:hover { color: var(--text-secondary); }
  127. .model-select {
  128. width: 100%; background: var(--bg-2); border: 1px solid var(--border);
  129. border-radius: var(--radius-sm); padding: 8px 10px;
  130. color: var(--text-primary); font-family: var(--sans); font-size: 0.82rem;
  131. outline: none; transition: border-color var(--transition);
  132. }
  133. .model-select:focus { border-color: var(--accent); }
  134. .model-select option { background: var(--bg-2); }
  135. .field-hint { font-size: 0.72rem; color: var(--text-muted); margin-top: 6px; }
  136. .field-hint a { color: var(--text-secondary); }
  137. .field-hint a:hover { color: var(--accent); }
  138. /* Buttons */
  139. .btn-row { display: flex; gap: 8px; margin-top: 16px; flex-wrap: wrap; }
  140. .btn {
  141. display: inline-flex; align-items: center; gap: 6px;
  142. padding: 9px 18px; border-radius: var(--radius-sm);
  143. font-family: var(--sans); font-size: 0.82rem; font-weight: 500;
  144. cursor: pointer; transition: all var(--transition); border: none;
  145. }
  146. .btn-primary { background: var(--accent); color: #0b0f0e; }
  147. .btn-primary:hover { background: #3bf59a; transform: translateY(-1px); }
  148. .btn-outline { background: transparent; color: var(--text-secondary); border: 1px solid var(--border-hover); }
  149. .btn-outline:hover { border-color: var(--accent); color: var(--accent); }
  150. .btn-ghost { background: transparent; color: var(--text-muted); border: 1px solid var(--border); }
  151. .btn-ghost:hover { border-color: var(--border-hover); color: var(--text-secondary); }
  152. .btn-danger-ghost { background: transparent; color: var(--danger); border: 1px solid rgba(240,128,128,0.3); }
  153. .btn-danger-ghost:hover { background: rgba(240,128,128,0.08); }
  154. /* Test result */
  155. .test-result {
  156. margin-top: 12px; padding: 10px 14px; border-radius: var(--radius-sm);
  157. font-size: 0.78rem; display: none;
  158. }
  159. .test-result.ok { background: var(--accent-dim); border: 1px solid rgba(45,220,138,0.25); color: var(--accent); }
  160. .test-result.fail { background: rgba(240,128,128,0.08); border: 1px solid rgba(240,128,128,0.25); color: var(--danger); }
  161. /* Active provider selector */
  162. .active-section {
  163. background: var(--bg-1); border: 1px solid var(--border);
  164. border-radius: var(--radius-lg); padding: 20px;
  165. margin-bottom: 24px;
  166. }
  167. .active-section h2 { font-size: 0.82rem; font-weight: 500; margin-bottom: 12px; color: var(--text-secondary); }
  168. .provider-option {
  169. display: flex; align-items: center; gap: 12px;
  170. padding: 10px 14px; border-radius: var(--radius-sm);
  171. border: 1px solid var(--border); background: var(--bg-2);
  172. cursor: pointer; transition: all var(--transition); margin-bottom: 8px;
  173. }
  174. .provider-option:last-child { margin-bottom: 0; }
  175. .provider-option:hover { border-color: var(--border-hover); }
  176. .provider-option.selected { border-color: var(--accent); background: var(--accent-dim); }
  177. .provider-option input[type=radio] { accent-color: var(--accent); flex-shrink: 0; }
  178. .provider-option-label { flex: 1; }
  179. .provider-option-name { font-size: 0.85rem; font-weight: 500; }
  180. .provider-option-detail { font-size: 0.72rem; color: var(--text-muted); margin-top: 1px; }
  181. .provider-option.disabled { opacity: 0.4; cursor: not-allowed; }
  182. .provider-option.disabled:hover { border-color: var(--border); }
  183. /* Divider */
  184. .divider { border: none; border-top: 1px solid var(--border); margin: 24px 0; }
  185. /* Spinner */
  186. .spinner {
  187. width: 13px; height: 13px; border: 2px solid var(--border);
  188. border-top-color: var(--accent); border-radius: 50%;
  189. animation: spin .65s linear infinite; display: inline-block;
  190. }
  191. @keyframes spin { to { transform: rotate(360deg); } }
  192. ::-webkit-scrollbar { width: 5px; }
  193. ::-webkit-scrollbar-track { background: transparent; }
  194. ::-webkit-scrollbar-thumb { background: var(--border-hover); border-radius: 3px; }
  195. </style>
  196. </head>
  197. <body>
  198. <nav class="site-nav">
  199. <div class="nav-inner">
  200. <a class="nav-brand" href="/">
  201. <svg width="22" height="22" viewBox="0 0 28 28" fill="none">
  202. <rect width="28" height="28" rx="6" fill="var(--accent-dim)" stroke="rgba(45,220,138,0.25)" stroke-width="1"/>
  203. <path d="M8 20 L14 8 L20 20" stroke="var(--accent)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
  204. <path d="M10.5 16 L17.5 16" stroke="var(--accent)" stroke-width="1.5" stroke-linecap="round"/>
  205. </svg>
  206. Tasmanian Planning Scheme
  207. </a>
  208. <a class="nav-back" href="/local_state-planning-scheme.php">
  209. <i class="bi bi-arrow-left"></i> Back to Assistant
  210. </a>
  211. </div>
  212. </nav>
  213. <div class="page">
  214. <div class="page-header">
  215. <h1>Bring your <em>own API key</em></h1>
  216. <p>Use Claude, GPT-4o or Grok as the AI behind your planning queries. Your Qdrant vector search and clause retrieval stay on our servers — only the final LLM call uses your key.</p>
  217. </div>
  218. <!-- Security notice -->
  219. <div class="security-notice">
  220. <i class="bi bi-shield-lock"></i>
  221. <p>
  222. <strong>Your key never leaves your browser.</strong>
  223. Keys are stored in <code style="font-size:0.78rem;color:var(--warn);">localStorage</code> only and sent
  224. directly to the provider's API — never to our servers. Anyone with access to
  225. this browser can read keys from DevTools. Use a key with
  226. <strong>spending limits</strong> set in your provider's dashboard.
  227. </p>
  228. </div>
  229. <!-- Active provider selector -->
  230. <div class="active-section">
  231. <h2><i class="bi bi-toggles" style="margin-right:6px;color:var(--accent);"></i>Active LLM provider</h2>
  232. <div id="providerOptions">
  233. <!-- Rendered by JS -->
  234. </div>
  235. </div>
  236. <hr class="divider">
  237. <!-- Provider config cards -->
  238. <div class="provider-grid" id="providerGrid">
  239. <!-- Rendered by JS -->
  240. </div>
  241. </div>
  242. <script>
  243. 'use strict';
  244. /* ── Storage keys ────────────────────────────────────────────────────── */
  245. const ACTIVE_KEY = 'tpr_byok_active'; // which provider is active: 'internal'|'anthropic'|'openai'|'grok'|'ollama'
  246. const KEY_PREFIX = 'tpr_byok_key_'; // + provider id
  247. const MODEL_PREFIX= 'tpr_byok_model_'; // + provider id
  248. /* ── Provider definitions ────────────────────────────────────────────── */
  249. const PROVIDERS = [
  250. {
  251. id: 'anthropic',
  252. name: 'Anthropic Claude',
  253. desc: 'claude-sonnet-4-5 — best reasoning for planning documents',
  254. icon: '✦',
  255. iconBg: '#1a1f2e',
  256. iconColor: '#c084fc',
  257. keyPlaceholder: 'sk-ant-api03-…',
  258. keyHint: 'Get your key at <a href="https://console.anthropic.com/keys" target="_blank" rel="noopener">console.anthropic.com/keys</a>. Set a monthly spend limit.',
  259. models: [
  260. { value: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5 (recommended)' },
  261. { value: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5 (faster, cheaper)' },
  262. { value: 'claude-opus-4-5', label: 'Claude Opus 4.5 (most capable)' },
  263. ],
  264. test: testAnthropic,
  265. },
  266. {
  267. id: 'openai',
  268. name: 'OpenAI',
  269. desc: 'gpt-4o-mini — fast and cost-effective',
  270. icon: '⬡',
  271. iconBg: '#0f2027',
  272. iconColor: '#74aa9c',
  273. keyPlaceholder: 'sk-proj-…',
  274. keyHint: 'Get your key at <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a>. Set usage limits.',
  275. models: [
  276. { value: 'gpt-4o-mini', label: 'GPT-4o mini (recommended)' },
  277. { value: 'gpt-4o', label: 'GPT-4o (more capable)' },
  278. { value: 'gpt-4.1-mini', label: 'GPT-4.1 mini' },
  279. ],
  280. test: testOpenAI,
  281. },
  282. {
  283. id: 'grok',
  284. name: 'xAI Grok',
  285. desc: 'grok-3-mini — OpenAI-compatible, strong reasoning',
  286. icon: '𝕏',
  287. iconBg: '#0a0a0a',
  288. iconColor: '#e5e5e5',
  289. keyPlaceholder: 'xai-…',
  290. keyHint: 'Get your key at <a href="https://console.x.ai" target="_blank" rel="noopener">console.x.ai</a>.',
  291. models: [
  292. { value: 'grok-3-mini', label: 'Grok 3 mini (recommended)' },
  293. { value: 'grok-3', label: 'Grok 3 (most capable)' },
  294. ],
  295. test: testOpenAICompat,
  296. },
  297. {
  298. id: 'ollama',
  299. name: 'Ollama (local)',
  300. desc: 'Your own local Ollama instance — full privacy',
  301. icon: '⬢',
  302. iconBg: '#0f1a0f',
  303. iconColor: '#2ddc8a',
  304. keyPlaceholder: 'http://localhost:11434',
  305. keyHint: 'Enter the base URL of your Ollama instance. No API key needed.',
  306. isUrlField: true,
  307. models: [
  308. { value: 'llama3.1:8b', label: 'llama3.1:8b' },
  309. { value: 'mistral:7b', label: 'mistral:7b' },
  310. { value: 'custom', label: 'Custom (type below)' },
  311. ],
  312. test: testOllama,
  313. },
  314. ];
  315. /* ── State ───────────────────────────────────────────────────────────── */
  316. function getActive() { return localStorage.getItem(ACTIVE_KEY) || 'internal'; }
  317. function setActive(id) { localStorage.setItem(ACTIVE_KEY, id); }
  318. function getKey(id) { return localStorage.getItem(KEY_PREFIX + id) || ''; }
  319. function setKey(id, val) { val ? localStorage.setItem(KEY_PREFIX + id, val) : localStorage.removeItem(KEY_PREFIX + id); }
  320. function getModel(id, fallback) { return localStorage.getItem(MODEL_PREFIX + id) || fallback || ''; }
  321. function setModel(id, val) { localStorage.setItem(MODEL_PREFIX + id, val); }
  322. function hasKey(id) { return !!getKey(id); }
  323. /* ── Render ──────────────────────────────────────────────────────────── */
  324. function render() {
  325. renderActiveSelector();
  326. renderProviderCards();
  327. }
  328. function renderActiveSelector() {
  329. const active = getActive();
  330. const wrap = document.getElementById('providerOptions');
  331. const options = [
  332. { id: 'internal', name: 'Our server ', detail: 'Uses the built-in custom model — no key needed', always: true },
  333. ...PROVIDERS.map(p => ({
  334. id: p.id, name: p.name,
  335. detail: hasKey(p.id) ? `Key configured · ${getModel(p.id, p.models[0].value)}` : 'No key set — configure below',
  336. always: false,
  337. }))
  338. ];
  339. wrap.innerHTML = options.map(o => {
  340. const sel = active === o.id;
  341. const disabled = !o.always && !hasKey(o.id);
  342. return `
  343. <label class="provider-option ${sel ? 'selected' : ''} ${disabled ? 'disabled' : ''}"
  344. onclick="${disabled ? 'event.preventDefault()' : `selectProvider('${o.id}')`}">
  345. <input type="radio" name="activeProvider" value="${o.id}"
  346. ${sel ? 'checked' : ''} ${disabled ? 'disabled' : ''}>
  347. <div class="provider-option-label">
  348. <div class="provider-option-name">${o.name}</div>
  349. <div class="provider-option-detail">${o.detail}</div>
  350. </div>
  351. ${sel ? '<i class="bi bi-check-circle-fill" style="color:var(--accent);font-size:1rem;"></i>' : ''}
  352. </label>`;
  353. }).join('');
  354. }
  355. function renderProviderCards() {
  356. const grid = document.getElementById('providerGrid');
  357. grid.innerHTML = PROVIDERS.map(p => {
  358. const key = getKey(p.id);
  359. const model = getModel(p.id, p.models[0].value);
  360. const hasK = !!key;
  361. const isActive= getActive() === p.id;
  362. const masked = key ? maskKey(key) : '';
  363. const modelOptions = p.models.map(m =>
  364. `<option value="${m.value}" ${model === m.value ? 'selected' : ''}>${m.label}</option>`
  365. ).join('');
  366. return `
  367. <div class="provider-card ${hasK ? 'has-key' : ''} ${isActive ? 'active-provider' : ''}" id="card-${p.id}">
  368. <div class="provider-header" onclick="toggleCard('${p.id}')">
  369. <div class="provider-logo" style="background:${p.iconBg};color:${p.iconColor};">
  370. ${p.icon}
  371. </div>
  372. <div class="provider-info">
  373. <div class="provider-name">${p.name}</div>
  374. <div class="provider-desc">${p.desc}</div>
  375. </div>
  376. <div class="provider-status">
  377. ${isActive ? '<span class="status-pill active"><i class="bi bi-stars"></i> Active</span>' :
  378. hasK ? '<span class="status-pill configured"><i class="bi bi-check2"></i> Configured</span>' :
  379. '<span class="status-pill not-set">Not set</span>'}
  380. </div>
  381. <i class="bi bi-chevron-down expand-icon" style="margin-left:10px;font-size:0.8rem;"></i>
  382. </div>
  383. <div class="provider-body" id="body-${p.id}">
  384. <div class="field-group">
  385. <label class="field-label">${p.isUrlField ? 'Base URL' : 'API Key'}</label>
  386. <div class="key-input-wrap">
  387. <input type="password" class="key-input" id="key-${p.id}"
  388. value="${esc(key)}"
  389. placeholder="${p.keyPlaceholder}"
  390. autocomplete="off" spellcheck="false">
  391. <button class="key-toggle" onclick="toggleKeyVis('${p.id}')" title="Show/hide">
  392. <i class="bi bi-eye" id="eye-${p.id}"></i>
  393. </button>
  394. </div>
  395. <p class="field-hint">${p.keyHint}</p>
  396. </div>
  397. <div class="field-group">
  398. <label class="field-label">Model</label>
  399. <select class="model-select" id="model-${p.id}"
  400. onchange="setModel('${p.id}', this.value)">
  401. ${modelOptions}
  402. </select>
  403. ${p.id === 'ollama' ? `
  404. <div id="ollama-custom-wrap" style="${model === 'custom' ? '' : 'display:none;'}margin-top:8px;">
  405. <input type="text" class="key-input" id="model-custom-${p.id}"
  406. style="font-family:var(--sans);"
  407. value="${model !== 'custom' ? model : ''}"
  408. placeholder="e.g. codellama:13b">
  409. </div>` : ''}
  410. </div>
  411. <div class="test-result" id="test-${p.id}"></div>
  412. <div class="btn-row">
  413. <button class="btn btn-primary" onclick="saveProvider('${p.id}')">
  414. <i class="bi bi-floppy"></i> Save
  415. </button>
  416. <button class="btn btn-outline" onclick="testProvider('${p.id}')">
  417. <i class="bi bi-lightning"></i> Test connection
  418. </button>
  419. ${hasK ? `<button class="btn btn-danger-ghost" onclick="removeProvider('${p.id}')">
  420. <i class="bi bi-trash3"></i> Remove key
  421. </button>` : ''}
  422. </div>
  423. </div>
  424. </div>`;
  425. }).join('');
  426. // Wire up Ollama custom model toggle
  427. document.getElementById('model-ollama')?.addEventListener('change', function() {
  428. const wrap = document.getElementById('ollama-custom-wrap');
  429. if (wrap) wrap.style.display = this.value === 'custom' ? '' : 'none';
  430. });
  431. }
  432. /* ── Interactions ────────────────────────────────────────────────────── */
  433. window.toggleCard = function(id) {
  434. const card = document.getElementById(`card-${id}`);
  435. card?.classList.toggle('expanded');
  436. };
  437. window.toggleKeyVis = function(id) {
  438. const input = document.getElementById(`key-${id}`);
  439. const eye = document.getElementById(`eye-${id}`);
  440. if (!input) return;
  441. const isHidden = input.type === 'password';
  442. input.type = isHidden ? 'text' : 'password';
  443. eye.className = isHidden ? 'bi bi-eye-slash' : 'bi bi-eye';
  444. };
  445. window.selectProvider = function(id) {
  446. setActive(id);
  447. render();
  448. };
  449. window.saveProvider = function(id) {
  450. const p = PROVIDERS.find(p => p.id === id);
  451. const keyEl = document.getElementById(`key-${id}`);
  452. const key = (keyEl?.value || '').trim();
  453. let model = document.getElementById(`model-${id}`)?.value || p?.models[0]?.value || '';
  454. if (id === 'ollama' && model === 'custom') {
  455. model = document.getElementById(`model-custom-${id}`)?.value.trim() || 'llama3.1:8b';
  456. }
  457. if (!key) {
  458. showTestResult(id, false, `Please enter a ${p?.isUrlField ? 'URL' : 'key'} first.`);
  459. return;
  460. }
  461. setKey(id, key);
  462. setModel(id, model);
  463. // If this is the only configured key, auto-select it
  464. if (getActive() === 'internal') setActive(id);
  465. showTestResult(id, true, 'Saved. Click "Test connection" to verify it works.');
  466. render();
  467. };
  468. window.removeProvider = function(id) {
  469. if (!confirm(`Remove ${PROVIDERS.find(p=>p.id===id)?.name} key?`)) return;
  470. setKey(id, '');
  471. if (getActive() === id) setActive('internal');
  472. render();
  473. };
  474. window.testProvider = async function(id) {
  475. const btn = document.querySelector(`#card-${id} .btn-outline`);
  476. const orig = btn?.innerHTML;
  477. if (btn) { btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Testing…'; }
  478. const key = document.getElementById(`key-${id}`)?.value || getKey(id);
  479. let model = document.getElementById(`model-${id}`)?.value || getModel(id);
  480. if (id === 'ollama' && model === 'custom')
  481. model = document.getElementById(`model-custom-${id}`)?.value || 'llama3.1:8b';
  482. const p = PROVIDERS.find(p => p.id === id);
  483. try {
  484. await p.test(key, model);
  485. showTestResult(id, true, `Connected to ${p.name} (${model}) ✓`);
  486. } catch(e) {
  487. showTestResult(id, false, `Failed: ${e.message}`);
  488. } finally {
  489. if (btn) { btn.disabled = false; btn.innerHTML = orig; }
  490. }
  491. };
  492. function showTestResult(id, ok, msg) {
  493. const el = document.getElementById(`test-${id}`);
  494. if (!el) return;
  495. el.className = `test-result ${ok ? 'ok' : 'fail'}`;
  496. el.innerHTML = `<i class="bi bi-${ok ? 'check-circle' : 'x-circle'}"></i> ${esc(msg)}`;
  497. el.style.display = 'block';
  498. }
  499. /* ── Provider test functions ─────────────────────────────────────────── */
  500. async function testAnthropic(key, model) {
  501. const res = await fetch('https://api.anthropic.com/v1/messages', {
  502. method: 'POST',
  503. headers: {
  504. 'Content-Type': 'application/json',
  505. 'x-api-key': key,
  506. 'anthropic-version': '2023-06-01',
  507. 'anthropic-dangerous-direct-browser-access': 'true',
  508. },
  509. body: JSON.stringify({
  510. model,
  511. max_tokens: 32,
  512. messages: [{ role: 'user', content: 'Reply with just the word CONNECTED.' }]
  513. })
  514. });
  515. if (!res.ok) {
  516. const err = await res.json().catch(() => ({}));
  517. throw new Error(err?.error?.message || `HTTP ${res.status}`);
  518. }
  519. const data = await res.json();
  520. const text = data?.content?.[0]?.text || '';
  521. if (!text) throw new Error('Empty response');
  522. }
  523. async function testOpenAI(key, model) {
  524. await testOpenAICompat(key, model, 'https://api.openai.com/v1');
  525. }
  526. async function testOpenAICompat(key, model, baseUrl = 'https://api.x.ai/v1') {
  527. const res = await fetch(`${baseUrl}/chat/completions`, {
  528. method: 'POST',
  529. headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` },
  530. body: JSON.stringify({
  531. model,
  532. max_tokens: 16,
  533. messages: [{ role: 'user', content: 'Reply with just the word CONNECTED.' }]
  534. })
  535. });
  536. if (!res.ok) {
  537. const err = await res.json().catch(() => ({}));
  538. throw new Error(err?.error?.message || `HTTP ${res.status}`);
  539. }
  540. }
  541. async function testOllama(baseUrl, model) {
  542. const url = baseUrl.replace(/\/$/, '') + '/api/generate';
  543. const res = await fetch(url, {
  544. method: 'POST',
  545. headers: { 'Content-Type': 'application/json' },
  546. body: JSON.stringify({ model, prompt: 'Reply with CONNECTED.', stream: false })
  547. });
  548. if (!res.ok) throw new Error(`HTTP ${res.status}`);
  549. }
  550. /* ── Utilities ───────────────────────────────────────────────────────── */
  551. function maskKey(key) {
  552. if (!key || key.length < 12) return '••••••••';
  553. return key.slice(0, 8) + '••••••••' + key.slice(-4);
  554. }
  555. function esc(s) {
  556. return String(s || '').replace(/[&<>"']/g, c =>
  557. ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c])
  558. );
  559. }
  560. /* ── Boot ────────────────────────────────────────────────────────────── */
  561. render();
  562. // Expand first card if no keys configured yet
  563. const configured = PROVIDERS.filter(p => hasKey(p.id));
  564. if (!configured.length) {
  565. document.getElementById('card-anthropic')?.classList.add('expanded');
  566. }
  567. </script>
  568. </body>
  569. </html>