Skip to content

add history primitive #600

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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/empty-spoons-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@browserbasehq/stagehand": minor
---

Added a `stagehand.history` array which stores an array of `act`, `extract`, `observe`, and `goto` calls made. Since this history array is stored on the `StagehandPage` level, it will capture methods even if indirectly called by an agent.
4 changes: 4 additions & 0 deletions evals/evals.config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
{
"tasks": [
{
"name": "history",
"categories": ["combination"]
},
{
"name": "expect_act_timeout",
"categories": ["act"]
Expand Down
54 changes: 54 additions & 0 deletions evals/tasks/history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { initStagehand } from "@/evals/initStagehand";
import { EvalFunction } from "@/types/evals";

export const history: EvalFunction = async ({ modelName, logger }) => {
const { stagehand, initResponse } = await initStagehand({
modelName,
logger,
});

const { debugUrl, sessionUrl } = initResponse;

await stagehand.page.goto("https://docs.stagehand.dev");

await stagehand.page.act("click on the 'Quickstart' tab");

await stagehand.page.extract("Extract the title of the page");

await stagehand.page.observe("Find all links on the page");

const history = stagehand.history;

const hasCorrectNumberOfEntries = history.length === 4;

const hasNavigateEntry = history[0].method === "navigate";
const hasActEntry = history[1].method === "act";
const hasExtractEntry = history[2].method === "extract";
const hasObserveEntry = history[3].method === "observe";

const allEntriesHaveTimestamps = history.every(
(entry) =>
typeof entry.timestamp === "string" && entry.timestamp.length > 0,
);
const allEntriesHaveResults = history.every(
(entry) => entry.result !== undefined,
);

await stagehand.close();

const success =
hasCorrectNumberOfEntries &&
hasNavigateEntry &&
hasActEntry &&
hasExtractEntry &&
hasObserveEntry &&
allEntriesHaveTimestamps &&
allEntriesHaveResults;

return {
_success: success,
debugUrl,
sessionUrl,
logs: logger.getLogs(),
};
};
56 changes: 49 additions & 7 deletions lib/StagehandPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Page, defaultExtractSchema } from "../types/page";
import {
ExtractOptions,
ExtractResult,
HistoryEntry,
ObserveOptions,
ObserveResult,
} from "../types/stagehand";
Expand Down Expand Up @@ -39,6 +40,11 @@ export class StagehandPage {
private userProvidedInstructions?: string;
private waitForCaptchaSolves: boolean;
private initialized: boolean = false;
private _history: Array<HistoryEntry> = [];

public get history(): ReadonlyArray<HistoryEntry> {
return this._history;
}

constructor(
page: PlaywrightPage,
Expand Down Expand Up @@ -294,6 +300,8 @@ export class StagehandPage {
? await this.api.goto(url, options)
: await target.goto(url, options);

this.addToHistory("navigate", { url, options }, result);

if (this.waitForCaptchaSolves) {
try {
await this.waitForCaptchaSolve(1000);
Expand Down Expand Up @@ -440,6 +448,19 @@ export class StagehandPage {
}
}

private addToHistory(
method: HistoryEntry["method"],
parameters: unknown,
result?: unknown,
): void {
this._history.push({
method,
parameters,
result: result ?? null,
timestamp: new Date().toISOString(),
});
}

async act(
actionOrOptions: string | ActOptions | ObserveResult,
): Promise<ActResult> {
Expand Down Expand Up @@ -501,6 +522,7 @@ export class StagehandPage {
if (this.api) {
const result = await this.api.act(actionOrOptions);
await this._refreshPageFromAPI();
this.addToHistory("act", actionOrOptions, result);
return result;
}

Expand Down Expand Up @@ -534,7 +556,7 @@ export class StagehandPage {
});

// `useVision` is no longer passed to the handler
return this.actHandler
const result = await this.actHandler
.act({
action,
llmClient,
Expand Down Expand Up @@ -569,6 +591,10 @@ export class StagehandPage {
action: action,
};
});

this.addToHistory("act", actionOrOptions, result);

return result;
}

async extract<T extends z.AnyZodObject = typeof defaultExtractSchema>(
Expand All @@ -582,10 +608,14 @@ export class StagehandPage {

// check if user called extract() with no arguments
if (!instructionOrOptions) {
let result: ExtractResult<T>;
if (this.api) {
return this.api.extract<T>({});
result = await this.api.extract<T>({});
} else {
result = await this.extractHandler.extract();
}
return this.extractHandler.extract();
this.addToHistory("extract", instructionOrOptions, result);
return result;
}

const options: ExtractOptions<T> =
Expand Down Expand Up @@ -615,7 +645,9 @@ export class StagehandPage {
}

if (this.api) {
return this.api.extract<T>(options);
const result = await this.api.extract<T>(options);
this.addToHistory("extract", instructionOrOptions, result);
return result;
}

const requestId = Math.random().toString(36).substring(2);
Expand Down Expand Up @@ -643,7 +675,7 @@ export class StagehandPage {
},
});

return this.extractHandler
const result = await this.extractHandler
.extract({
instruction,
schema,
Expand Down Expand Up @@ -676,6 +708,10 @@ export class StagehandPage {

throw e;
});

this.addToHistory("extract", instructionOrOptions, result);

return result;
}

async observe(
Expand Down Expand Up @@ -729,7 +765,9 @@ export class StagehandPage {
}

if (this.api) {
return this.api.observe(options);
const result = await this.api.observe(options);
this.addToHistory("observe", instructionOrOptions, result);
return result;
}

const requestId = Math.random().toString(36).substring(2);
Expand Down Expand Up @@ -761,7 +799,7 @@ export class StagehandPage {
},
});

return this.observeHandler
const result = await this.observeHandler
.observe({
instruction,
llmClient,
Expand Down Expand Up @@ -802,6 +840,10 @@ export class StagehandPage {

throw e;
});

this.addToHistory("observe", instructionOrOptions, result);

return result;
}

async getCDPClient(): Promise<CDPSession> {
Expand Down
11 changes: 11 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
AgentConfig,
StagehandMetrics,
StagehandFunctionName,
HistoryEntry,
} from "../types/stagehand";
import { StagehandContext } from "./StagehandContext";
import { StagehandPage } from "./StagehandPage";
Expand Down Expand Up @@ -899,6 +900,16 @@ export class Stagehand {
},
};
}

public get history(): ReadonlyArray<HistoryEntry> {
if (!this.stagehandPage) {
throw new Error(
"History is only available after a page has been initialized",
);
}

return this.stagehandPage.history;
}
}

export * from "../types/browser";
Expand Down
7 changes: 7 additions & 0 deletions types/stagehand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,10 @@ export enum StagehandFunctionName {
EXTRACT = "EXTRACT",
OBSERVE = "OBSERVE",
}

export interface HistoryEntry {
method: "act" | "extract" | "observe" | "navigate";
parameters: unknown;
result: unknown;
timestamp: string;
}