{"record":{"id":"0b88e94b0813e331","repo":"apify/crawlee","slug":"stagehand-act-failed-improveerrormessage-erro","errorCode":null,"errorMessage":"Stagehand act() failed: ${improveErrorMessage(error)}","messagePattern":"Stagehand act\\(\\) failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/stagehand-crawler/src/internals/utils/stagehand-utils.ts","lineNumber":71,"sourceCode":" * ```\n *\n * @ignore\n */\nexport function enhancePageWithStagehand(page: Page, stagehand: Stagehand): StagehandPage {\n    // Cast to StagehandPage to add properties\n    const enhancedPage = page as StagehandPage;\n\n    /**\n     * Perform an action on the page using natural language.\n     * Passes this specific page to Stagehand so it operates on the correct page.\n     */\n    enhancedPage.act = async (instruction: string, options?: Omit<ActOptions, 'page'>) => {\n        try {\n            // Pass the page option to ensure Stagehand operates on this specific page\n            // Cast needed because Stagehand types reference older playwright-core versions\n            return await stagehand.act(instruction, { ...options, page: page as ActOptions['page'] });\n        } catch (error) {\n            throw new Error(`Stagehand act() failed: ${improveErrorMessage(error)}`, {\n                cause: error,\n            });\n        }\n    };\n\n    /**\n     * Extract structured data from the page using natural language and a Zod schema.\n     * Passes this specific page to Stagehand so it operates on the correct page.\n     */\n    enhancedPage.extract = async <T>(\n        instruction: string,\n        schema: ZodType<T>,\n        options?: Omit<ExtractOptions, 'page'>,\n    ): Promise<T> => {\n        try {\n            // Pass the page option to ensure Stagehand operates on this specific page\n            // Cast needed because Stagehand types reference older playwright-core versions\n            return await stagehand.extract(instruction, schema, { ...options, page: page as ExtractOptions['page'] });","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/apify/crawlee/blob/dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c/packages/stagehand-crawler/src/internals/utils/stagehand-utils.ts#L53-L89","documentation":"enhancePageWithStagehand wraps Stagehand's act() so crawler pages can drive AI actions. Any exception from stagehand.act() (element not found, LLM failure, timeout, Stagehand internal error) is rethrown as 'Stagehand act() failed: <improved message>' with the original attached as cause.","triggerScenarios":"Calling page.act('instruction') when Stagehand cannot complete the action: the instruction matched no element, the LLM/API call failed (invalid/missing API key, rate limit), the page navigated mid-action, or Stagehand's page reference went stale.","commonSituations":"Missing OPENAI_API_KEY / model credentials, vague act() instructions that match nothing, page closed or navigated between extract and act, network egress blocked to the LLM provider.","solutions":["Read the improved message and err.cause; if it's an auth error, set the correct API key env var for the configured model","Make act() instructions specific (target text/role) so Stagehand can resolve an element","Verify LLM provider connectivity and quota/rate limits","Re-check the page is open and idle before act(); retry once after a short delay on transient failures","Pin/upgrade @browserbasehq/stagehand if the cause points to an internal Stagehand bug"],"exampleFix":"// before\nawait page.act('click the thing');\n// after\ntry {\n    await page.act('Click the \"Sign in\" button in the header');\n} catch (err) {\n    log.warning('act failed', err.cause ?? err);\n    await page.act('Click the button with text \"Sign in\"');\n}","handlingStrategy":"try-catch","validationCode":"if (!process.env.OPENAI_API_KEY && !process.env.ANTHROPIC_API_KEY) {\n    throw new Error('Set an LLM API key before calling page.act()');\n}","typeGuard":"const isActFailure = (e) => e instanceof Error && e.message.startsWith('Stagehand act() failed:');","tryCatchPattern":"try {\n    await page.act('Click the \"Add to cart\" button');\n} catch (err) {\n    if (isActFailure(err)) log.warning('act failed', err.cause ?? err);\n    // fall back to a plain Playwright click\n    await page.click('text=Add to cart').catch(() => {});\n}","preventionTips":["Set and verify LLM provider credentials before the crawl starts","Write precise act() instructions","Wrap AI actions with a DOM-selector fallback for critical flows","Add retry/backoff for rate-limit causes"],"tags":["stagehand","ai","act","llm"],"backgroundTag":"stagehand-action-failed","analyzedSha":"dbe57fb09ca607ad59dcf998f3925ef9ac3bb26c","analyzedAt":"2026-08-30T22:22:28.328Z","schemaVersion":2},"datasetVersion":"2026-08-30T23:17:21.991Z"}