Run Stagehand on Steel
Stagehand is a library for browser automation in natural language. Its act and extract calls take an instruction such as "click the sign-in button" instead of a selector, and a model finds the element. With Steel, Stagehand drives a Steel session over the Chrome DevTools Protocol (CDP). You start Stagehand in its local mode and give it the session's CDP URL, so Stagehand does not launch a browser of its own. Proxies, CAPTCHA solving and the live view come from the session.
Stagehand has TypeScript and Python SDKs, and their APIs differ. In Python, Stagehand runs a local server, and act and extract return a stream of events.
Before you begin
- For TypeScript, Node.js 20.19+ or 22.12+. For Python, Python 3.10 or later.
- A Steel API key in the
STEEL_API_KEYenvironment variable. See API keys. - A key for Stagehand's model. The programs on this page use OpenAI, with the key in
OPENAI_API_KEY.
Install Stagehand 3 and the Steel SDK. The programs on this page do not work with Stagehand 4. When Stagehand 4 connects, it loads a browser extension from a folder on your machine, and a Steel session refuses that request.
npm install @browserbasehq/stagehand@3 steel-sdk zodpython3 -m venv .venv
source .venv/bin/activate
pip install "stagehand<4" steel-sdkSet up the integration
Connect Stagehand to a session
This program creates a session, connects Stagehand to the session's CDP URL, opens Hacker News and extracts the first five stories. It closes Stagehand and releases the session in finally. CDP explains the URL.
import { Stagehand } from "@browserbasehq/stagehand";
import Steel from "steel-sdk";
import { z } from "zod";
const client = new Steel();
const session = await client.sessions.create();
console.log("Session viewer:", session.sessionViewerUrl);
const stagehand = new Stagehand({
env: "LOCAL",
localBrowserLaunchOptions: {
cdpUrl: session.websocketUrl,
},
model: { modelName: "openai/gpt-6.1-sol", apiKey: process.env.OPENAI_API_KEY },
});
try {
await stagehand.init();
const page = await stagehand.context.awaitActivePage();
await page.goto("https://news.ycombinator.com");
const { stories } = await stagehand.extract(
"extract the titles and ranks of the first 5 stories on the page",
z.object({
stories: z.array(z.object({ title: z.string(), rank: z.number() })),
}),
);
for (const story of stories) {
console.log(`${story.rank}. ${story.title}`);
}
} finally {
await stagehand.close();
await client.sessions.release(session.id);
}import asyncio
import os
from stagehand import AsyncStagehand
from steel import Steel
STORY_SCHEMA = {
"type": "object",
"properties": {
"stories": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {"type": "string", "description": "Story title"},
"rank": {"type": "integer", "description": "Story rank number"},
},
"required": ["title", "rank"],
},
}
},
"required": ["stories"],
}
async def stream_result(stream):
result = None
async for event in stream:
if event.type == "log":
continue
if event.data.status == "finished":
result = event.data.result
elif event.data.status == "error":
raise RuntimeError(event.data.error or "unknown error")
return result
async def main():
client = Steel()
session = client.sessions.create()
print("Session viewer:", session.session_viewer_url)
stagehand = AsyncStagehand(
server="local",
model_api_key=os.environ["OPENAI_API_KEY"],
local_ready_timeout_s=30.0,
)
try:
started = await stagehand.sessions.start(
model_name="openai/gpt-6.1-sol",
browser={
"type": "local",
"launchOptions": {
"cdpUrl": session.websocket_url,
},
},
)
stagehand_id = started.data.session_id
try:
await stagehand.sessions.navigate(
id=stagehand_id, url="https://news.ycombinator.com"
)
stream = await stagehand.sessions.extract(
id=stagehand_id,
instruction="Extract the titles and ranks of the first 5 stories on the page",
schema=STORY_SCHEMA,
stream_response=True,
x_stream_response="true",
)
data = await stream_result(stream)
for story in data["stories"]:
print(f"{story['rank']}. {story['title']}")
finally:
await stagehand.sessions.end(id=stagehand_id)
finally:
await stagehand.close()
client.sessions.release(session.id)
asyncio.run(main())The Python file is not named stagehand.py, because that name would hide the stagehand package from the import. In Python, Stagehand has its own session ID, stagehand_id. It is not the Steel session's ID.
Run the program
npx tsx stagehand.mtspython stagehand_steel.pyThe program prints the session viewer URL, then the rank and title of the first five stories on Hacker News. The stories change from run to run.
Session viewer: https://app.steel.dev/sessions/f6630a88-fbfd-422e-8f9f-b2a90cdc9d0eAct on the page
act takes an instruction and clicks, types or scrolls. Add it after extract:
await stagehand.act("click the 'new' link in the top navigation");stream = await stagehand.sessions.act(
id=stagehand_id,
input="click the 'new' link in the top navigation",
stream_response=True,
x_stream_response="true",
)
await stream_result(stream)Add Steel features to the session
Pass session options to client.sessions.create(). Stagehand does not see them. For example, this session uses a Steel proxy and solves CAPTCHAs:
const session = await client.sessions.create({
useProxy: true,
solveCaptcha: true,
});session = client.sessions.create(use_proxy=True, solve_captcha=True)On Launch, Steel proxies and CAPTCHA solving need a verified account, as Verify a Launch account explains. Session configuration lists every option.
Next steps
- Stagehand 3 documentation:
act,extract, models and settings, for the version that the programs use. - Cookbook starters: TypeScript and Python.