Skip to content

Commit 823092d

Browse files
committed
Added local example
1 parent cb804fc commit 823092d

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

examples/local_example.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
Example demonstrating how to run Stagehand in local mode using the SEA binary
3+
that ships with the PyPI wheel.
4+
5+
Required environment variables:
6+
- BROWSERBASE_API_KEY (can be any value in local mode)
7+
- BROWSERBASE_PROJECT_ID (can be any value in local mode)
8+
- MODEL_API_KEY (used for client configuration even in local mode)
9+
- OPENAI_API_KEY (used by the SEA server for LLM access)
10+
11+
Install the published wheel before running this script:
12+
`pip install stagehand-alpha`
13+
Then execute this example with the same interpreter:
14+
`python examples/local_example.py`
15+
"""
16+
17+
import os
18+
import sys
19+
20+
from stagehand import Stagehand
21+
22+
23+
def main() -> None:
24+
openai_key = os.environ.get("OPENAI_API_KEY")
25+
if not openai_key:
26+
sys.exit("Set the OPENAI_API_KEY environment variable to run the local server.")
27+
28+
client = Stagehand(
29+
server="local",
30+
local_openai_api_key=openai_key,
31+
local_ready_timeout_s=30.0,
32+
)
33+
34+
session_id: str | None = None
35+
36+
try:
37+
print("⏳ Starting local session (this will start the embedded SEA binary)...")
38+
session = client.sessions.start(
39+
model_name="openai/gpt-5-nano",
40+
browser={
41+
"type": "local",
42+
"launchOptions": {
43+
"headless": True,
44+
},
45+
},
46+
)
47+
session_id = session.data.session_id
48+
print(f"✅ Session started: {session_id}")
49+
50+
print("🌐 Navigating to https://www.example.com...")
51+
client.sessions.navigate(
52+
id=session_id,
53+
url="https://www.example.com",
54+
frame_id="",
55+
)
56+
print("✅ Navigation complete")
57+
58+
print("🔍 Extracting the main heading text...")
59+
extract_response = client.sessions.extract(
60+
id=session_id,
61+
instruction="Extract the text of the top-level heading on this page.",
62+
)
63+
print(f"📄 Extracted data: {extract_response.data.result}")
64+
65+
except Exception as exc:
66+
print(f"❌ Encountered an error: {exc}")
67+
raise
68+
finally:
69+
if session_id:
70+
print("🛑 Ending session...")
71+
client.sessions.end(id=session_id)
72+
print("✅ Session ended")
73+
print("🔌 Closing client (shuts down the SEA server)...")
74+
client.close()
75+
print("✅ Local server shut down")
76+
77+
78+
if __name__ == "__main__":
79+
main()

0 commit comments

Comments
 (0)