Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/curly-rules-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@browserbasehq/stagehand": minor
---

Added support for offloading agent tasks to the API.
12 changes: 12 additions & 0 deletions lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ import { GotoOptions } from "../types/playwright";
import {
ActOptions,
ActResult,
AgentConfig,
ExtractOptions,
ExtractResult,
ObserveOptions,
ObserveResult,
} from "../types/stagehand";
import { AgentExecuteOptions, AgentResult } from ".";

export class StagehandAPI {
private apiKey: string;
Expand Down Expand Up @@ -112,6 +114,16 @@ export class StagehandAPI {
});
}

async agentExecute(
agentConfig: AgentConfig,
executeOptions: AgentExecuteOptions,
): Promise<AgentResult> {
return this.execute<AgentResult>({
method: "agentExecute",
args: { agentConfig, executeOptions },
});
}

async end(): Promise<Response> {
const url = `/sessions/${this.sessionId}/end`;
return await this.request(url, {
Expand Down
26 changes: 26 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,32 @@ export class Stagehand {
throw new Error("Instruction is required for agent execution");
}

if (this.usingAPI) {
if (!this.apiClient) {
throw new Error(
"API client not initialized. Ensure that you have initialized Stagehand via `await stagehand.init()`.",
);
}

if (!options.options) {
options.options = {};
}

if (options.provider === "anthropic") {
options.options.apiKey = process.env.ANTHROPIC_API_KEY;
} else if (options.provider === "openai") {
options.options.apiKey = process.env.OPENAI_API_KEY;
}

if (!options.options.apiKey) {
throw new Error(
`API key not found for \`${options.provider}\` provider. Please set the ${options.provider === "anthropic" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"} environment variable or pass an apiKey in the options object.`,
);
}

return await this.apiClient.agentExecute(options, executeOptions);
}

return await agentHandler.execute(executeOptions);
},
};
Expand Down
2 changes: 1 addition & 1 deletion types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export interface StagehandAPIConstructorParams {
}

export interface ExecuteActionParams {
method: "act" | "extract" | "observe" | "navigate" | "end";
method: "act" | "extract" | "observe" | "navigate" | "end" | "agentExecute";
args?: unknown;
params?: unknown;
}
Expand Down