Building a Multi-Model AI Assistant Browser Extension: From Model Selection to a Working Setup

    This guide walks through building a browser extension that puts several AI models behind one side panel. It explains when a unified entry point pays off, how to route tasks across reasoning, vision, code, image, and lightweight models with fallback chains, whether to install a third-party extension or build your own Manifest V3 extension, why accounts and session history belong on the backend, how to design a daily-plus-signup quota system, and what a minimal pre-launch security checklist and MVP path look like. It includes a runnable Python router example and a troubleshooting table.

    1. Start Here: a Unified Entry Point Pays Off by Consolidating, not by Piling Up Models

    Whether a unified entry point is worth building depends on one thing: can it consolidate scattered steps into a single place? Compare the two approaches:

    Dimension Every site on its own Unified entry point
    Accounts N separate sign-ups and sets of credentials One backend account system
    Context Each site keeps its own records; nothing is shared Sessions persisted in one place
    Switching Jump, log in, dig up the right page Dropdown switch inside the side panel
    Cost Quotas scattered and easily wasted Centralized metering and fallback
    Privacy risk Fragmented and hard to control Unified masking plus a domain allowlist

    2. How to Pick a Model: One Table and One Decision Tree

    Task type Typical cases Cost strategy Quality trade-off Fallback model
    Reasoning / long text Solution analysis, long-form rewriting Medium (3 points per call) High, slow Light model
    Visual understanding Screenshot Q&A, chart interpretation Higher (5 points per call) High Reasoning model (degrades to text-only)
    Code Completion, debugging, scripts Medium (3 points per call) High, still needs human review Reasoning model
    Image generation Assets, illustrative diagrams High (8 points per call) Medium, results are non-deterministic None: reject outright and tell the user
    Lightweight Polishing, summaries, rewriting Low (1 point per call) Medium It is the fallback itself

    Decision tree: Is there an image? → route to vision. Is the output code? → route to code. Is the input over 8k characters, or does it need multi-step reasoning? → route to reasoning. Is it just rewording? → route to the light model. Is quota running low? → step down one level along the fallback chain. Still short at the end of the fallback chain? → clearly tell the user “today’s quota is used up”; do not force a low-quality model to produce an answer.

    3. Install a Prebuilt Extension, or Build Your Own?

    Route A: a third-party extension. Vet the source first: who is behind the store listing and who the developer is, how often it is updated, whether the permission list matches the advertised functionality, and whether the privacy policy explains where data goes. The risk is that your prompts are sent to the vendor’s servers, so never paste internal material directly.

    Route B: build your own extension (more control). Four requirements are non-negotiable: Manifest V3, the side panel as the host surface, least privilege, and a network request domain allowlist.

    1. {
    2. "manifest_version": 3,
    3. "name": "Multi-Model Side Panel",
    4. "version": "0.1.0",
    5. "permissions": ["sidePanel", "storage"],
    6. "host_permissions": ["https://your-gateway.example.com/*"],
    7. "side_panel": { "default_path": "panel.html" },
    8. "background": { "service_worker": "sw.js" }
    9. }

    Key points: host_permissions should contain only your own gateway domain, never <all_urls>; API keys are stored on the gateway side only and must never be written into the manifest, panel.html, or any frontend bundle, because extension packages can be unpacked and inspected; sidePanel.setPanelBehavior is what opens the panel directly when the icon is clicked.

    4. Account Management Belongs on the Backend

    The extension frontend handles only UI and short-lived token custody. Registration, verification, and sessions all live on the backend. What matters:

    • Use email plus a verification code, or third-party OAuth, for sign-in, and never store plaintext passwords in the frontend.
    • Issue a short-lived access token plus a refresh token, and keep them in chrome.storage.session (invalidated when the browser session closes) rather than persisting them long term in localStorage.
    • Return 401 when the session expires and refresh silently; show the login prompt only if the refresh fails.
    • Cross-device sync relies on a backend session table plus history fetched by user_id.
    • Account security notes should include alerts for sign-ins from unfamiliar locations and one-click logout of all devices.

    5. Decide Which Side Stores Session History Before You Build

    “Continue the conversation later” is not a UI problem, it is a storage problem. Local storage keeps only the current device, and clearing the cache loses everything. Backend storage is what makes cross-device continuation possible, but it raises data retention periods and the right to deletion. Answer two questions before choosing: how long is data retained, and how does a user delete it?

    6. Quota Mechanics: Data Model and Deduction Flow

    Quota is two-part: a daily quota plus a sign-up bonus. The daily quota resets on calendar days (in the user’s timezone); the sign-up bonus is granted once and consumed first. For concurrency, apply a per-user_id semaphore limit (1–2 is a reasonable suggestion) and perform the deduction atomically after the call succeeds, so failed calls are not charged. Store it in a single row, user_quota(user_id, bonus, day, used, daily_limit), use a conditional update to stay safe under concurrency, and return 429 with the remaining quota whenever the limit is exceeded.

    7. Architecture: an Adapter Layer Hides the Differences, a Routing Layer Schedules Work (Runnable Example)

    The only dependency is the Python 3.9+ standard library, and pointing GATEWAY at your own gateway is enough to get it running. Production requires replacing authentication, retries, and quota storage.

    1. import json, os, time, threading, urllib.error, urllib.request
    2. GATEWAY = os.environ.get("AI_GATEWAY", "http://127.0.0.1:8080")
    3. # Gateway contract: POST /v1/chat, Header: Authorization: Bearer <short-lived token>
    4. # Error codes: 401 invalid auth / 429 rate limited or out of quota / 503 backend unavailable
    5. def call_backend(model, messages, token, timeout=15.0, retries=2):
    6. body = json.dumps({"model": model, "messages": messages, "stream": False}).encode()
    7. last = None
    8. for i in range(retries + 1):
    9. req = urllib.request.Request(GATEWAY + "/v1/chat", data=body, headers={
    10. "Content-Type": "application/json", "Authorization": "Bearer " + token})
    11. try:
    12. with urllib.request.urlopen(req, timeout=timeout) as r:
    13. return json.loads(r.read()).get("text", "")
    14. except urllib.error.HTTPError as e:
    15. if e.code in (401, 429):
    16. raise RuntimeError("gateway_error:%d" % e.code) # do not retry
    17. last = e
    18. except (urllib.error.URLError, TimeoutError) as e:
    19. last = e
    20. time.sleep(0.5 * 2 ** i) # exponential backoff
    21. raise RuntimeError("gateway_unavailable:%s" % last)
    22. class Adapter:
    23. def __init__(self, model): self.model = model
    24. def chat(self, messages, token): return call_backend(self.model, messages, token)
    25. class Quota:
    26. """In-process implementation for demo purposes; production needs a database plus atomic deduction"""
    27. def __init__(self, daily=100, signup=200): self.daily, self.signup, self.s, self.lk = daily, signup, {}, threading.Lock()
    28. def _row(self, u):
    29. today = time.strftime("%Y-%m-%d")
    30. r = self.s.setdefault(u, {"bonus": self.signup, "day": today, "used": 0})
    31. if r["day"] != today: r["day"], r["used"] = today, 0
    32. return r
    33. def can_afford(self, u, cost):
    34. with self.lk:
    35. r = self._row(u); return r["bonus"] + (self.daily - r["used"]) >= cost
    36. def charge(self, u, cost):
    37. with self.lk:
    38. r = self._row(u); b = min(r["bonus"], cost)
    39. r["bonus"] -= b; r["used"] += cost - b
    40. COST = {"light": (1, None), "reasoning": (3, "light"), "code": (3, "reasoning"),
    41. "vision": (5, "reasoning"), "image": (8, None)}
    42. class Router:
    43. def __init__(self, quota): self.q, self.a = quota, {k: Adapter(k) for k in COST}
    44. def dispatch(self, task, messages, user, token):
    45. task = task if task in self.a else "reasoning"
    46. for _ in range(len(COST)):
    47. cost, fb = COST[task]
    48. if self.q.can_afford(user, cost):
    49. try:
    50. out = self.a[task].chat(messages, token)
    51. self.q.charge(user, cost) # deduct only after success
    52. return out
    53. except RuntimeError as e:
    54. print("log", task, str(e)) # structured log: task / error code / latency
    55. task = fb
    56. return "Quota exhausted or all backends are unavailable; please retry later"
    57. if __name__ == "__main__":
    58. print(Router(Quota()).dispatch("code", [{"role": "user", "content": "Write a batch rename script"}], "alice", "dev-token"))

    The routing policy can additionally score candidates by remaining quota, latency, and cost weights. An empty fallback for image means outright rejection rather than a forced answer.

    8. Pre-Launch Security Checklist for the Extension

    • Request least privilege, and state the purpose to the user whenever permissions change.
    • Keep host_permissions to a domain allowlist.
    • Keep keys on the gateway only; never push them down to the frontend.
    • Mask sensitive content locally with regular expressions before sending.
    • Write a privacy notice that covers data flows, retention periods, and where to request deletion.
    • Clear storage on uninstall or logout.

    9. Common Mistakes and Troubleshooting

    Symptom Common cause Fix
    “Permission denied” prompt Missing sidePanel or the host is not authorized Add the permission and reload the extension
    401 keeps recurring Token expired and refresh failed Sign in again
    429 Rate limited or quota exhausted Fall back to a cheaper model or retry the next day
    Request timeout No timeout set, or no retry 15s timeout plus exponential backoff
    Off-target output Model hallucination Human review of code and compliance conclusions
    Blank panel Service worker error Check the extension error logs

    10. The Minimum Path to Production

    An MVP should cover one scenario only (for example, screenshot Q&A), with acceptance criteria of: switching models takes fewer than 2 steps, timeouts and exhausted quota both surface a message, and failures can fall back. Add history and cross-device sync in a two-week iteration; track daily active users, success rate, and points spent per user. Keep a feature switch in the rollback plan so you can revert to a single model with one click. Get the select–call–verify loop closed first, then extend to multimodal and creative tasks.