| 42 | |
| 43 | |
| 44 | async def handle_model_switching( |
| 45 | req_id: str, context: RequestContext |
| 46 | ) -> RequestContext: |
| 47 | set_request_id(req_id) |
| 48 | if not context["needs_model_switching"]: |
| 49 | return context |
| 50 | |
| 51 | logger = context["logger"] |
| 52 | page = context["page"] |
| 53 | model_switching_lock = context["model_switching_lock"] |
| 54 | model_id_to_use = context["model_id_to_use"] |
| 55 | |
| 56 | # Assert non-None values required for model switching |
| 57 | assert page is not None, "Page must be ready for model switching" |
| 58 | assert model_id_to_use is not None, "Target model ID must be set" |
| 59 | |
| 60 | async with model_switching_lock: |
| 61 | if state.current_ai_studio_model_id != model_id_to_use: |
| 62 | logger.info( |
| 63 | f"[{req_id}] Preparing to switch model: {state.current_ai_studio_model_id} -> {model_id_to_use}" |
| 64 | ) |
| 65 | from browser_utils import switch_ai_studio_model |
| 66 | |
| 67 | switch_success = await switch_ai_studio_model(page, model_id_to_use, req_id) |
| 68 | if switch_success: |
| 69 | state.current_ai_studio_model_id = model_id_to_use |
| 70 | context["model_actually_switched"] = True |
| 71 | context["current_ai_studio_model_id"] = model_id_to_use |
| 72 | logger.info( |
| 73 | f"[{req_id}] ✅ Model switched successfully: {state.current_ai_studio_model_id}" |
| 74 | ) |
| 75 | else: |
| 76 | # Current model ID should exist when switching fails |
| 77 | current_model = state.current_ai_studio_model_id or "unknown" |
| 78 | await _handle_model_switch_failure( |
| 79 | req_id, |
| 80 | page, |
| 81 | model_id_to_use, |
| 82 | current_model, |
| 83 | logger, |
| 84 | ) |
| 85 | |
| 86 | return context |
| 87 | |
| 88 | |
| 89 | async def _handle_model_switch_failure( |