byok-settings.php 27 KB

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