1+ import asyncio
2+ import logging
3+ import os
4+
5+ from dotenv import load_dotenv
6+ from rich .console import Console
7+ from rich .panel import Panel
8+ from rich .theme import Theme
9+
10+ from stagehand import Stagehand , StagehandConfig , configure_logging
11+
12+ # Create a custom theme for consistent styling
13+ custom_theme = Theme (
14+ {
15+ "info" : "cyan" ,
16+ "success" : "green" ,
17+ "warning" : "yellow" ,
18+ "error" : "red bold" ,
19+ "highlight" : "magenta" ,
20+ "url" : "blue underline" ,
21+ }
22+ )
23+
24+ # Create a Rich console instance with our theme
25+ console = Console (theme = custom_theme )
26+
27+ load_dotenv ()
28+
29+ # Configure logging with the utility function
30+ configure_logging (
31+ level = logging .INFO , # Set to INFO for regular logs, DEBUG for detailed
32+ quiet_dependencies = True , # Reduce noise from dependencies
33+ )
34+
35+ async def main ():
36+ # Build a unified configuration object for Stagehand
37+ config = StagehandConfig (
38+ env = "LOCAL" ,
39+ system_prompt = "You are a browser automation assistant that helps users navigate websites effectively." ,
40+ model_client_options = {"apiKey" : os .getenv ("MODEL_API_KEY" )},
41+ verbose = 2 ,
42+ )
43+
44+ # Create a Stagehand client using the configuration object.
45+ stagehand = Stagehand (config )
46+
47+ # Initialize - this creates a new session automatically.
48+ console .print ("\n 🚀 [info]Initializing Stagehand...[/]" )
49+ await stagehand .init ()
50+
51+ console .print ("\n ▶️ [highlight] Navigating[/] to Google" )
52+ await stagehand .page .goto ("https://google.com/" )
53+ console .print ("✅ [success]Navigated to Google[/]" )
54+
55+ console .print ("\n ▶️ [highlight] Using Agent to perform a task[/]: playing a game of 2048" )
56+ agent = stagehand .agent (
57+ model = "gemini-2.5-computer-use-preview-10-2025" ,
58+ instructions = "You are a helpful web navigation assistant that helps users find information. You are currently on the following page: google.com. Do not ask follow up questions, the user will trust your judgement." ,
59+ options = {"apiKey" : os .getenv ("GEMINI_API_KEY" )}
60+ )
61+ agent_result = await agent .execute (
62+ instruction = "Play a game of 2048" ,
63+ max_steps = 20 ,
64+ auto_screenshot = True ,
65+ )
66+
67+ console .print (agent_result )
68+
69+ console .print ("📊 [info]Agent execution result:[/]" )
70+ console .print (f"🎯 Completed: [bold]{ 'Yes' if agent_result .completed else 'No' } [/]" )
71+ if agent_result .message :
72+ console .print (f"💬 Message: [italic]{ agent_result .message } [/]" )
73+
74+ if agent_result .actions :
75+ console .print (f"🔄 Actions performed: [bold]{ len (agent_result .actions )} [/]" )
76+ for i , action in enumerate (agent_result .actions ):
77+ action_type = action .type
78+
79+ console .print (f" Action { i + 1 } : { action_type if action_type else 'Unknown' } " )
80+
81+ # For debugging, you can also print the full JSON
82+ console .print ("[dim]Full response JSON:[/]" )
83+ console .print_json (f"{ agent_result .model_dump_json ()} " )
84+
85+ # Close the session
86+ console .print ("\n ⏹️ [warning]Closing session...[/]" )
87+ await stagehand .close ()
88+ console .print ("✅ [success]Session closed successfully![/]" )
89+ console .rule ("[bold]End of Example[/]" )
90+
91+
92+ if __name__ == "__main__" :
93+ # Add a fancy header
94+ console .print (
95+ "\n " ,
96+ Panel (
97+ "[light_gray]Stagehand 🤘 Agent Example[/]" ,
98+ border_style = "green" ,
99+ padding = (1 , 10 ),
100+ ),
101+ )
102+ asyncio .run (main ())
0 commit comments