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.
{"manifest_version": 3,"name": "Multi-Model Side Panel","version": "0.1.0","permissions": ["sidePanel", "storage"],"host_permissions": ["https://your-gateway.example.com/*"],"side_panel": { "default_path": "panel.html" },"background": { "service_worker": "sw.js" }}
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 inlocalStorage. - 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.
import json, os, time, threading, urllib.error, urllib.requestGATEWAY = os.environ.get("AI_GATEWAY", "http://127.0.0.1:8080")# Gateway contract: POST /v1/chat, Header: Authorization: Bearer <short-lived token># Error codes: 401 invalid auth / 429 rate limited or out of quota / 503 backend unavailabledef call_backend(model, messages, token, timeout=15.0, retries=2):body = json.dumps({"model": model, "messages": messages, "stream": False}).encode()last = Nonefor i in range(retries + 1):req = urllib.request.Request(GATEWAY + "/v1/chat", data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + token})try:with urllib.request.urlopen(req, timeout=timeout) as r:return json.loads(r.read()).get("text", "")except urllib.error.HTTPError as e:if e.code in (401, 429):raise RuntimeError("gateway_error:%d" % e.code) # do not retrylast = eexcept (urllib.error.URLError, TimeoutError) as e:last = etime.sleep(0.5 * 2 ** i) # exponential backoffraise RuntimeError("gateway_unavailable:%s" % last)class Adapter:def __init__(self, model): self.model = modeldef chat(self, messages, token): return call_backend(self.model, messages, token)class Quota:"""In-process implementation for demo purposes; production needs a database plus atomic deduction"""def __init__(self, daily=100, signup=200): self.daily, self.signup, self.s, self.lk = daily, signup, {}, threading.Lock()def _row(self, u):today = time.strftime("%Y-%m-%d")r = self.s.setdefault(u, {"bonus": self.signup, "day": today, "used": 0})if r["day"] != today: r["day"], r["used"] = today, 0return rdef can_afford(self, u, cost):with self.lk:r = self._row(u); return r["bonus"] + (self.daily - r["used"]) >= costdef charge(self, u, cost):with self.lk:r = self._row(u); b = min(r["bonus"], cost)r["bonus"] -= b; r["used"] += cost - bCOST = {"light": (1, None), "reasoning": (3, "light"), "code": (3, "reasoning"),"vision": (5, "reasoning"), "image": (8, None)}class Router:def __init__(self, quota): self.q, self.a = quota, {k: Adapter(k) for k in COST}def dispatch(self, task, messages, user, token):task = task if task in self.a else "reasoning"for _ in range(len(COST)):cost, fb = COST[task]if self.q.can_afford(user, cost):try:out = self.a[task].chat(messages, token)self.q.charge(user, cost) # deduct only after successreturn outexcept RuntimeError as e:print("log", task, str(e)) # structured log: task / error code / latencytask = fbreturn "Quota exhausted or all backends are unavailable; please retry later"if __name__ == "__main__":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_permissionsto 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
storageon 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.
