|
| 1 | +""" |
| 2 | +Example demonstrating how to run an extract() call with streaming logs enabled |
| 3 | +using the remote Browserbase Stagehand service. |
| 4 | +
|
| 5 | +Required environment variables: |
| 6 | +- BROWSERBASE_API_KEY: Your Browserbase API key |
| 7 | +- BROWSERBASE_PROJECT_ID: Your Browserbase project ID |
| 8 | +- MODEL_API_KEY: Your OpenAI API key |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | + |
| 13 | +from stagehand import AsyncStagehand |
| 14 | + |
| 15 | + |
| 16 | +async def main() -> None: |
| 17 | + # Create client using environment variables |
| 18 | + async with AsyncStagehand( |
| 19 | + browserbase_api_key=os.environ.get("BROWSERBASE_API_KEY"), |
| 20 | + browserbase_project_id=os.environ.get("BROWSERBASE_PROJECT_ID"), |
| 21 | + model_api_key=os.environ.get("MODEL_API_KEY"), |
| 22 | + ) as client: |
| 23 | + # Start a new browser session with verbose logging enabled |
| 24 | + session = await client.sessions.create( |
| 25 | + model_name="openai/gpt-5-nano", |
| 26 | + verbose=2, |
| 27 | + ) |
| 28 | + |
| 29 | + print(f"Session started: {session.id}") |
| 30 | + |
| 31 | + try: |
| 32 | + print("Navigating to https://www.example.com...") |
| 33 | + await session.navigate(url="https://www.example.com") |
| 34 | + print("Navigation complete.") |
| 35 | + |
| 36 | + print("\nExtracting the page heading with streaming logs...") |
| 37 | + stream = await session.extract( |
| 38 | + instruction="Extract the text of the top-level heading on this page.", |
| 39 | + schema={ |
| 40 | + "type": "object", |
| 41 | + "properties": { |
| 42 | + "headingText": { |
| 43 | + "type": "string", |
| 44 | + "description": "The text content of the top-level heading", |
| 45 | + }, |
| 46 | + "subheadingText": { |
| 47 | + "type": "string", |
| 48 | + "description": "Optional subheading text below the main heading", |
| 49 | + }, |
| 50 | + }, |
| 51 | + "required": ["headingText"], |
| 52 | + }, |
| 53 | + stream_response=True, |
| 54 | + x_stream_response="true", |
| 55 | + ) |
| 56 | + |
| 57 | + result_payload: object | None = None |
| 58 | + async for event in stream: |
| 59 | + if event.type == "log": |
| 60 | + print(f"[log] {event.data.message}") |
| 61 | + continue |
| 62 | + |
| 63 | + status = event.data.status |
| 64 | + print(f"[system] status={status}") |
| 65 | + if status == "finished": |
| 66 | + result_payload = event.data.result |
| 67 | + elif status == "error": |
| 68 | + error_message = event.data.error or "unknown error" |
| 69 | + raise RuntimeError(f"Stream reported error: {error_message}") |
| 70 | + |
| 71 | + print("Extract completed successfully!") |
| 72 | + print(f"Payload received: {result_payload}") |
| 73 | + finally: |
| 74 | + await session.end() |
| 75 | + print("\nSession ended.") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + import asyncio |
| 80 | + |
| 81 | + asyncio.run(main()) |
0 commit comments