|
| 1 | +#!/usr/bin/env -S rye run python |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import List |
| 5 | + |
| 6 | +from pydantic import BaseModel |
| 7 | + |
| 8 | +from browser_use_sdk import AsyncBrowserUse |
| 9 | +from browser_use_sdk.types.task_create_params import AgentSettings |
| 10 | + |
| 11 | +# gets API Key from environment variable BROWSER_USE_API_KEY |
| 12 | +client = AsyncBrowserUse() |
| 13 | + |
| 14 | + |
| 15 | +# Regular Task |
| 16 | +async def stream_regular_task(): |
| 17 | + regular_task = await client.tasks.create( |
| 18 | + task=""" |
| 19 | + Find top 10 Hacker News articles and return the title and url. |
| 20 | + """, |
| 21 | + agent_settings=AgentSettings(llm="gemini-2.5-flash"), |
| 22 | + ) |
| 23 | + |
| 24 | + print(f"Regular Task ID: {regular_task.id}") |
| 25 | + |
| 26 | + async for res in client.tasks.stream(regular_task.id): |
| 27 | + print(f"Regular Task Status: {res.status}") |
| 28 | + |
| 29 | + if len(res.steps) > 0: |
| 30 | + last_step = res.steps[-1] |
| 31 | + print(f"Regular Task Step: {last_step.url} ({last_step.next_goal})") |
| 32 | + for action in last_step.actions: |
| 33 | + print(f" - Regular Task Action: {action}") |
| 34 | + |
| 35 | + print("Regular Task Done") |
| 36 | + |
| 37 | + |
| 38 | +# Structured Output |
| 39 | +async def stream_structured_task(): |
| 40 | + class HackerNewsPost(BaseModel): |
| 41 | + title: str |
| 42 | + url: str |
| 43 | + |
| 44 | + class SearchResult(BaseModel): |
| 45 | + posts: List[HackerNewsPost] |
| 46 | + |
| 47 | + structured_task = await client.tasks.create( |
| 48 | + task=""" |
| 49 | + Find top 10 Hacker News articles and return the title and url. |
| 50 | + """, |
| 51 | + structured_output_json=SearchResult, |
| 52 | + ) |
| 53 | + |
| 54 | + print(f"Structured Task ID: {structured_task.id}") |
| 55 | + |
| 56 | + async for res in client.tasks.stream(structured_task.id, structured_output_json=SearchResult): |
| 57 | + print(f"Structured Task Status: {res.status}") |
| 58 | + |
| 59 | + if res.status == "finished": |
| 60 | + if res.parsed_output is None: |
| 61 | + print("Structured Task No output") |
| 62 | + else: |
| 63 | + for post in res.parsed_output.posts: |
| 64 | + print(f" - Structured Task Post: {post.title} - {post.url}") |
| 65 | + break |
| 66 | + |
| 67 | + print("Structured Task Done") |
| 68 | + |
| 69 | + |
| 70 | +# Main |
| 71 | + |
| 72 | + |
| 73 | +async def main(): |
| 74 | + await asyncio.gather( |
| 75 | + # |
| 76 | + stream_regular_task(), |
| 77 | + stream_structured_task(), |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +asyncio.run(main()) |
0 commit comments