Skip to main content
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 Caching

Enable automatic action caching to eliminate redundant LLM calls. Simply specify a cacheDir when initializing Stagehand:
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  cacheDir: "action-cache", // Enable automatic caching
});

await stagehand.init();

// First run: uses LLM inference and caches
// Subsequent runs: reuses cached action (no LLM cost)
await stagehand.act("Click the sign in button");

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(prompt: string) {
  const models = ["google/gemini-2.5-flash", "openai/gpt-4o"];

  for (const model of models) {
    try {
      const stagehand = new Stagehand({
        env: "LOCAL",
        model: model
      });
      await stagehand.init();
      const [action] = await stagehand.observe(prompt);
      await stagehand.act(action);
      await stagehand.close();
      return;
    } catch (error) {
      console.log(`Falling back to ${model}...`);
      await stagehand.close();
    }
  }
}

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 = await 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;
  }
}