Skip to content

在保持自动化效果的同时,降低 Stagehand 的 LLM 推理成本与浏览器基础设施成本。

文档索引

可在此获取完整文档索引:https://docs.stagehand.dev/llms.txt

在进一步浏览前,可使用该文件发现所有可用页面。

在保持自动化性能的同时尽可能降低成本

Stagehand 中的成本优化,核心是在 LLM 推理成本与浏览器基础设施成本之间取得平衡。本指南提供了一些可直接落地的实用策略,帮助你减少自动化开销。

先从这些简单的优化开始,它们通常就能帮助你显著降低成本。

对于简单任务,我们不建议使用更大、更昂贵的高级模型。你可以查看我们的评测结果,比较不同任务类型下各模型的性能与成本。

模型选择指南

根据你的预算和准确率要求选择合适的 LLM。

评测结果

查看不同模型在不同任务中的表现。

启用自动操作缓存,可以消除重复的 LLM 调用。只需在初始化 Stagehand 时指定 cacheDir

const stagehand = new Stagehand({
env: "BROWSERBASE",
cacheDir: "action-cache", // 启用自动缓存
});
await stagehand.init();
// 首次运行:使用 LLM 推理并写入缓存
// 后续运行:复用已缓存的操作(不再产生 LLM 成本)
await stagehand.act("Click the sign in button");

缓存指南

了解如何组织缓存以及管理缓存目录。

在可能的情况下复用会话,并设置合适的超时时间。更多细节可参考浏览器配置

const stagehand = new Stagehand({
env: "BROWSERBASE",
browserbaseSessionCreateParams: {
timeout: 1800, // 30 分钟,而不是默认的 1 小时
keepAlive: true, // 在任务之间保持会话存活
}
});

Browserbase 成本优化

优化 Browserbase 基础设施成本与会话管理。

对于简单任务,自动回退到更便宜的模型:

// 根据任务复杂度,从低成本模型逐步回退到高成本模型
// 性能对比请参见 stagehand.dev/evals
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();
}
}
}

在多个任务之间复用浏览器会话:

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

跟踪你的花费,有助于发现优化空间。详细指标请参见可观测性指南

// 监控 token 使用量
const metrics = await stagehand.metrics;
console.log(`Total tokens: ${metrics.totalPromptTokens + metrics.totalCompletionTokens}`);
console.log(`Estimated cost: $${(metrics.totalPromptTokens + metrics.totalCompletionTokens) * 0.00001}`);

可观测性与指标

实时监控使用模式并跟踪成本。

设置支出上限,避免产生意外成本:

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

模型选择指南

根据你的预算和准确率要求选择合适的 LLM。

缓存策略

通过智能操作缓存与观察模式来降低成本。

可观测性与指标

监控使用模式并实时跟踪成本。

浏览器配置

优化 Browserbase 基础设施成本与会话管理。

-
0:000:00