browser-assistant 2.9.41 → 2.9.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,9 +18,11 @@
18
18
  return error;
19
19
  }
20
20
  function temporary(error) {
21
- // The backend already tried the available vision keys.
22
- if (error.code === 'vision_rate_limited')
21
+ if (error.code === 'vision_request_too_large')
23
22
  return false;
23
+ // Retry exhausted vision keys only after their explicit cooldown expires.
24
+ if (error.code === 'vision_rate_limited')
25
+ return Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0;
24
26
  const text = error?.message || '';
25
27
  if (/access denied|forbidden|unauthorized|invalid.api.key|not configured|validation|not.support|model.*(?:not found|not exist)|illustration changed|question changed|context invalidated|extension was reloaded|no readable|unparseable/i.test(text))
26
28
  return false;
@@ -48,7 +50,7 @@
48
50
  catch (error) {
49
51
  if (!active())
50
52
  return null;
51
- if (attempt === attempts || !temporary(error) || error.retryAfterMs > 60_000)
53
+ if (attempt === attempts || !temporary(error) || error.retryAfterMs > 300_000)
52
54
  throw error;
53
55
  onRetry({ attempt: attempt + 1, attempts, message: error.message });
54
56
  // Short waits keep Stop/Pause responsive. Revalidate before the
@@ -57,6 +59,8 @@
57
59
  for (let elapsed = 0; elapsed < delay; elapsed += 100) {
58
60
  if (!active())
59
61
  return null;
62
+ if (!current())
63
+ throw new Error('Question changed while requesting an answer. No answer was selected.');
60
64
  await sleep(Math.min(100, delay - elapsed));
61
65
  }
62
66
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.41",
4
+ "version": "2.9.43",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.41",
3
+ "version": "2.9.43",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -2,6 +2,10 @@
2
2
  GROQ_API_KEY=
3
3
  GROQ_API_KEY_2=
4
4
  GROQ_API_KEY_3=
5
+ GROQ_API_KEY_4=
6
+ GROQ_API_KEY_5=
7
+ GROQ_API_KEY_6=
8
+ GROQ_API_KEY_7=
5
9
  GROQ_TEXT_MODEL=openai/gpt-oss-120b
6
10
  GROQ_VISION_MODEL=qwen/qwen3.8-27b
7
11
  # Optional comma-separated vision models available on YOUR account; empty by default.
package/server/main.py CHANGED
@@ -1,5 +1,6 @@
1
1
  import os
2
2
  import json
3
+ import copy
3
4
  import asyncio
4
5
  import ast
5
6
  import math
@@ -41,11 +42,16 @@ logger = logging.getLogger("browser-assistant")
41
42
  load_dotenv(Path(__file__).with_name('.env'))
42
43
 
43
44
  # Setup Groq — multiple API keys for rate-limit rotation
44
- _groq_keys = []
45
- for env_var in ["GROQ_API_KEY", "GROQ_API_KEY_2", "GROQ_API_KEY_3"]:
46
- key = os.getenv(env_var)
47
- if key and key != "your_groq_api_key_here" and key not in _groq_keys:
48
- _groq_keys.append(key)
45
+ def load_groq_keys():
46
+ """Load up to seven distinct configured credentials in stable order."""
47
+ keys = []
48
+ for env_var in ["GROQ_API_KEY", *[f"GROQ_API_KEY_{i}" for i in range(2, 8)]]:
49
+ key = os.getenv(env_var, "").strip()
50
+ if key and key != "your_groq_api_key_here" and key not in keys:
51
+ keys.append(key)
52
+ return keys
53
+
54
+ _groq_keys = load_groq_keys()
49
55
 
50
56
  # Retry rotation is handled below. Disable the SDK's long exponential retry so
51
57
  # a rate-limited key cannot hold up every next question before we try another.
@@ -195,7 +201,7 @@ async def lifespan(_app: FastAPI):
195
201
  client.close()
196
202
 
197
203
 
198
- app = FastAPI(title="Browser Assistant API", version="2.9.41", lifespan=lifespan)
204
+ app = FastAPI(title="Browser Assistant API", version="2.9.43", lifespan=lifespan)
199
205
  install_local_guards(app)
200
206
 
201
207
  @app.exception_handler(HTTPException)
@@ -1648,7 +1654,7 @@ async def _solve_vision(content: VisionContent):
1648
1654
  compressed = []
1649
1655
  for index, image in enumerate(inputs, 1):
1650
1656
  try:
1651
- compressed.append(await asyncio.to_thread(compress_image_base64, image, max_dim=2400, quality=95))
1657
+ compressed.append(await asyncio.to_thread(compress_image_base64, image, max_dim=1600, quality=95))
1652
1658
  except ValueError as exc:
1653
1659
  raise HTTPException(422, f'Image {index}: {exc}') from exc
1654
1660
  is_code_scan = content.practice_type == "code" or (content.practice_type == "auto" and bool(content.language))
@@ -1685,7 +1691,9 @@ async def _solve_vision(content: VisionContent):
1685
1691
  def reset_at(key):
1686
1692
  return _vision_key_cooldowns.get((vision_model, key), 0.0)
1687
1693
 
1688
- attempts = len(clients) + 1
1694
+ attempts = len(clients) + 3
1695
+ image_sizes = iter((1280, 1024))
1696
+ messages = copy.deepcopy(messages)
1689
1697
  for attempt in range(attempts):
1690
1698
  now = loop.time()
1691
1699
  key = next((index for index in key_order if reset_at(index) <= now), None)
@@ -1696,7 +1704,7 @@ async def _solve_vision(content: VisionContent):
1696
1704
  def call_vision_api(c=client, m=vision_model):
1697
1705
  return c.chat.completions.create(
1698
1706
  model=m,
1699
- messages=messages,
1707
+ messages=copy.deepcopy(messages),
1700
1708
  temperature=0.0,
1701
1709
  max_completion_tokens=max(4096, vision_token_limit) if len(image_blocks) > 3 else vision_token_limit,
1702
1710
  **options,
@@ -1715,6 +1723,25 @@ async def _solve_vision(content: VisionContent):
1715
1723
  except Exception as exc:
1716
1724
  error_text = str(exc)
1717
1725
  provider_status = getattr(exc, 'status_code', None)
1726
+ if provider_status == 413:
1727
+ size = next(image_sizes, None)
1728
+ if size is None:
1729
+ raise HTTPException(413, detail={
1730
+ 'code': 'vision_request_too_large',
1731
+ 'message': 'The complete vision request exceeds the provider input limit even after image resizing. Send a smaller clear image or use text input; repeating this request will not help.',
1732
+ }) from exc
1733
+ resized = False
1734
+ for message in messages:
1735
+ for block in message.get('content', []) if isinstance(message.get('content'), list) else []:
1736
+ if block.get('type') == 'image_url':
1737
+ encoded = await asyncio.to_thread(compress_image_base64, block['image_url']['url'], max_dim=size, quality=95)
1738
+ block['image_url']['url'] = 'data:image/jpeg;base64,' + encoded
1739
+ resized = True
1740
+ if not resized:
1741
+ raise HTTPException(413, detail={'code': 'vision_request_too_large',
1742
+ 'message': 'The vision text request exceeds the provider input limit. Reduce the supplied context.'}) from exc
1743
+ logger.info('Vision input too large; retrying with complete images limited to %d pixels.', size)
1744
+ continue
1718
1745
  if provider_status == 429 or (provider_status is None and re.search(r'\b429\b|\brate[_ ]limit', error_text, re.I)):
1719
1746
  delay = vision_retry_after(exc, error_text)
1720
1747
  _vision_key_cooldowns[(vision_model, key)] = max(reset_at(key), loop.time() + delay)
@@ -1875,6 +1902,8 @@ async def _solve_vision(content: VisionContent):
1875
1902
  unconfirmed = True
1876
1903
  errors.append(f"{vision_model}: {exc}")
1877
1904
  logger.warning(errors[-1])
1905
+ except HTTPException:
1906
+ raise
1878
1907
  except Exception as exc:
1879
1908
  errors.append(f"{vision_model}: {exc}")
1880
1909
  logger.warning(errors[-1])
@@ -102,6 +102,8 @@ async def collect_image_evidence(blocks, positions, question, model, complete, b
102
102
  except VisionRateLimitError:
103
103
  raise
104
104
  except Exception as exc:
105
+ if getattr(exc, 'status_code', None) == 413:
106
+ raise
105
107
  raise RuntimeError(f'Image batch {ids} could not be processed: {exc}') from exc
106
108
  # Network retries belong to the provider wrapper; completed batches stay intact.
107
109
  return json.dumps({'logical_image_positions': positions, 'images': evidence}, ensure_ascii=False)