> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stagehand.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost Optimization

> Minimize costs while maintaining automation performance

export const V3Banner = () => null;

<V3Banner />

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](https://stagehand.dev/evals) for model performance and cost comparisons across different task types.

<CardGroup cols={2}>
  <Card title="Model Selection Guide" icon="brain" href="/configuration/models">
    Choose the right LLM for your budget and accuracy requirements
  </Card>

  <Card title="Evaluation Results" icon="chart-line" href="https://www.stagehand.dev/evals">
    See how different models perform on different tasks
  </Card>
</CardGroup>

### 2. Implement Caching

Enable automatic action caching to eliminate redundant LLM calls. Simply specify a `cacheDir` when initializing Stagehand:

```typescript theme={null}
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");
```

<CardGroup cols={1}>
  <Card title="Caching Guide" icon="database" href="/best-practices/caching">
    Learn how to organize caches and manage cache directories
  </Card>
</CardGroup>

### 3. Optimize Browser Sessions

Reuse sessions when possible and set appropriate timeouts. See [Browser Configuration](/configuration/browser) for details:

```typescript theme={null}
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  browserbaseSessionCreateParams: {
    timeout: 1800, // 30 minutes instead of default 1 hour
    keepAlive: true, // Keep session alive between tasks
  }
});
```

<CardGroup cols={1}>
  <Card title="Browserbase Cost Optimization" icon="window-maximize" href="https://docs.browserbase.com/guides/cost-optimization">
    Optimize Browserbase infrastructure costs and session management
  </Card>
</CardGroup>

## Advanced Strategies

### Intelligent Model Switching

Automatically fall back to cheaper models for simple tasks:

```typescript theme={null}
// 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:

```typescript theme={null}
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](/configuration/observability) for detailed metrics:

```typescript theme={null}
// 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}`);
```

<CardGroup cols={1}>
  <Card title="Observability & Metrics" icon="chart-line" href="/configuration/observability">
    Monitor usage patterns and track costs in real-time
  </Card>
</CardGroup>

## Budget Controls

Set spending limits to prevent unexpected costs:

```typescript theme={null}
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;
  }
}
```

## Related Resources

<CardGroup cols={2}>
  <Card title="Model Selection Guide" icon="brain" href="/configuration/models">
    Choose the right LLM for your budget and accuracy requirements
  </Card>

  <Card title="Caching Strategies" icon="database" href="/best-practices/caching">
    Reduce costs with smart action caching and observe patterns
  </Card>

  <Card title="Observability & Metrics" icon="chart-line" href="/configuration/observability">
    Monitor usage patterns and track costs in real-time
  </Card>

  <Card title="Browser Configuration" icon="window-maximize" href="/configuration/browser">
    Optimize Browserbase infrastructure costs and session management
  </Card>
</CardGroup>
