Cost optimization in Stagehand involves balancing LLM inference costs and browser infrastructure costs. This guide provides practical strategies to reduce your automation expenses.

Quick Wins

Start with these simple optimizations that can reduce costs:

1. Use the Right Model for the Job

We don’t recommend using larger, more premium models for simple tasks. See our evaluation results for model performance and cost comparisons across different task types.

2. Implement Smart Caching

Cache successful actions to avoid repeated LLM calls. Learn the basics in our Caching Guide:
// Cache successful actions
const [action] = await page.observe("Click the sign in button");
await setCache("sign_in_button", action);

// Reuse cached action (no LLM cost)
const cachedAction = await getCache("sign_in_button");
if (cachedAction) {
  await page.act(cachedAction);
} else {
  await page.act(action);
}

3. Optimize Browser Sessions

Reuse sessions when possible and set appropriate timeouts. See Browser Configuration for details:
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionCreateParams: {
    timeout: 1800, // 30 minutes instead of default 1 hour
    keepAlive: true, // Keep session alive between tasks
  }
});

Advanced Strategies

Intelligent Model Switching

Automatically fall back to cheaper models for simple tasks:
// Use models from least to most expensive based on task complexity
// See stagehand.dev/evals for performance comparisons
async function smartAct(page: Page, prompt: string) {
  const models = ["cheaper-model", "premium-model"];
  
  for (const model of models) {
    try {
      const stagehand = new Stagehand({ modelName: model });
      await stagehand.init();
      const [action] = await stagehand.page.observe(prompt);
      await stagehand.page.act(action);
      return;
    } catch (error) {
      console.log(`Falling back to ${model}...`);
    }
  }
}

Session Pooling

Reuse browser sessions across multiple tasks:
class SessionManager {
  private sessions = new Map<string, Stagehand>();
  
  async getSession(taskType: string): Promise<Stagehand> {
    if (this.sessions.has(taskType)) {
      return this.sessions.get(taskType)!;
    }
    
    const stagehand = new Stagehand({ env: "BROWSERBASE" });
    await stagehand.init();
    this.sessions.set(taskType, stagehand);
    return stagehand;
  }
}

Cost Monitoring

Track your spending to identify optimization opportunities. See our Observability Guide for detailed metrics:
// Monitor token usage
const metrics = stagehand.metrics;
console.log(`Total tokens: ${metrics.totalPromptTokens + metrics.totalCompletionTokens}`);
console.log(`Estimated cost: $${(metrics.totalPromptTokens + metrics.totalCompletionTokens) * 0.00001}`);

Budget Controls

Set spending limits to prevent unexpected costs:
class BudgetGuard {
  private dailySpend = 0;
  private maxDailyBudget: number;
  
  constructor(maxDailyBudget: number = 25) {
    this.maxDailyBudget = maxDailyBudget;
  }
  
  checkBudget(estimatedCost: number): void {
    if (this.dailySpend + estimatedCost > this.maxDailyBudget) {
      throw new Error(`Daily budget exceeded: $${this.maxDailyBudget}`);
    }
    this.dailySpend += estimatedCost;
  }
}