Skip to content

Commit cec5a41

Browse files
committed
Minimal working byob example
1 parent 90a6f9d commit cec5a41

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

examples/byob_example.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from __future__ import annotations
2+
3+
"""
4+
Example showing how to bring your own browser driver while still using Stagehand.
5+
6+
This script runs Playwright locally to drive the browser and uses Stagehand to
7+
plan the interactions (observe → extract) without having Stagehand own the page.
8+
9+
Required environment variables:
10+
- BROWSERBASE_API_KEY
11+
- BROWSERBASE_PROJECT_ID
12+
- MODEL_API_KEY
13+
14+
Usage:
15+
16+
```
17+
pip install playwright stagehand-alpha
18+
# (if Playwright is new) playwright install chromium
19+
uv run python examples/byob_example.py
20+
```
21+
"""
22+
23+
import os
24+
import asyncio
25+
26+
from playwright.async_api import async_playwright
27+
28+
from stagehand import AsyncStagehand
29+
30+
31+
async def main() -> None:
32+
async with AsyncStagehand(
33+
browserbase_api_key=os.environ.get("BROWSERBASE_API_KEY"),
34+
browserbase_project_id=os.environ.get("BROWSERBASE_PROJECT_ID"),
35+
model_api_key=os.environ.get("MODEL_API_KEY"),
36+
) as client, async_playwright() as playwright:
37+
browser = await playwright.chromium.launch(headless=True)
38+
page = await browser.new_page()
39+
session = await client.sessions.create(model_name="openai/gpt-5-nano")
40+
41+
try:
42+
target_url = "https://news.ycombinator.com"
43+
await page.goto(target_url, wait_until="networkidle")
44+
await session.navigate(url=target_url)
45+
46+
print("🎯 Navigated Playwright to Hacker News; Stagehand tracks the same URL.")
47+
48+
print("🔄 Syncing Stagehand to the current Playwright URL:", page.url)
49+
await session.navigate(url=page.url)
50+
51+
extract_response = await session.extract(
52+
instruction="extract the primary headline on the page",
53+
schema={
54+
"type": "object",
55+
"properties": {"headline": {"type": "string"}},
56+
"required": ["headline"],
57+
},
58+
)
59+
60+
print("🧮 Stagehand extraction result:", extract_response.data.result)
61+
finally:
62+
await session.end()
63+
await browser.close()
64+
65+
66+
if __name__ == "__main__":
67+
asyncio.run(main())

0 commit comments

Comments
 (0)