Switch AI Studio model
(page: AsyncPage, model_id: str, req_id: str)
| 19 | |
| 20 | |
| 21 | async def switch_ai_studio_model(page: AsyncPage, model_id: str, req_id: str) -> bool: |
| 22 | """Switch AI Studio model""" |
| 23 | logger.info(f"[Model] Switching to -> {model_id}") |
| 24 | original_prefs_str: Optional[str] = None |
| 25 | _original_prompt_model: Optional[str] = None |
| 26 | new_chat_url = f"https://{AI_STUDIO_URL_PATTERN}prompts/new_chat" |
| 27 | |
| 28 | try: |
| 29 | original_prefs_str = await page.evaluate( |
| 30 | "() => localStorage.getItem('aiStudioUserPreference')" |
| 31 | ) |
| 32 | if original_prefs_str: |
| 33 | try: |
| 34 | original_prefs_obj = json.loads(original_prefs_str) |
| 35 | _original_prompt_model = original_prefs_obj.get("promptModel") |
| 36 | except json.JSONDecodeError: |
| 37 | logger.warning( |
| 38 | "Failed to parse original aiStudioUserPreference JSON string." |
| 39 | ) |
| 40 | original_prefs_str = None |
| 41 | |
| 42 | current_prefs_for_modification = ( |
| 43 | json.loads(original_prefs_str) if original_prefs_str else {} |
| 44 | ) |
| 45 | full_model_path = f"models/{model_id}" |
| 46 | |
| 47 | if current_prefs_for_modification.get("promptModel") == full_model_path: |
| 48 | logger.debug(f"[Model] Already at target model {model_id}") |
| 49 | if page.url != new_chat_url: |
| 50 | logger.debug( |
| 51 | f"[Model] URL is not new_chat, navigating to {new_chat_url}" |
| 52 | ) |
| 53 | await page.goto( |
| 54 | new_chat_url, wait_until="domcontentloaded", timeout=30000 |
| 55 | ) |
| 56 | await expect_async(page.locator(INPUT_SELECTOR)).to_be_visible( |
| 57 | timeout=30000 |
| 58 | ) |
| 59 | return True |
| 60 | |
| 61 | logger.debug( |
| 62 | f"[Model] Updating localStorage.promptModel: {current_prefs_for_modification.get('promptModel', 'unknown')} -> {full_model_path}" |
| 63 | ) |
| 64 | current_prefs_for_modification["promptModel"] = full_model_path |
| 65 | await page.evaluate( |
| 66 | "(prefsStr) => localStorage.setItem('aiStudioUserPreference', prefsStr)", |
| 67 | json.dumps(current_prefs_for_modification), |
| 68 | ) |
| 69 | |
| 70 | # Use new forced setting feature |
| 71 | logger.debug("[State] Applying forced UI state settings...") |
| 72 | ui_state_success = await _verify_and_apply_ui_state(page, req_id) |
| 73 | if not ui_state_success: |
| 74 | logger.warning( |
| 75 | "UI state setting failed, but continuing model switching flow" |
| 76 | ) |
| 77 | |
| 78 | # To maintain compatibility, also update current prefs object |