|
| 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 import AsyncBrowserUse |
| 9 | + |
| 10 | +# gets API Key from environment variable BROWSER_USE_API_KEY |
| 11 | +client = AsyncBrowserUse() |
| 12 | + |
| 13 | + |
| 14 | +# Regular Task |
| 15 | +async def retrieve_regular_task() -> None: |
| 16 | + """ |
| 17 | + Retrieves a regular task and waits for it to finish. |
| 18 | + """ |
| 19 | + |
| 20 | + print("Retrieving regular task...") |
| 21 | + |
| 22 | + regular_task = await client.tasks.create_task( |
| 23 | + task=""" |
| 24 | + Find top 10 Hacker News articles and return the title and url. |
| 25 | + """, |
| 26 | + llm="gemini-2.5-flash", |
| 27 | + ) |
| 28 | + |
| 29 | + print(f"Regular Task ID: {regular_task.id}") |
| 30 | + |
| 31 | + while True: |
| 32 | + regular_status = await client.tasks.get_task(regular_task.id) |
| 33 | + print(f"Regular Task Status: {regular_status.status}") |
| 34 | + if regular_status.status == "finished": |
| 35 | + print(f"Regular Task Output: {regular_status.output}") |
| 36 | + break |
| 37 | + |
| 38 | + await asyncio.sleep(1) |
| 39 | + |
| 40 | + print("Done") |
| 41 | + |
| 42 | + |
| 43 | +async def retrieve_structured_task() -> None: |
| 44 | + """ |
| 45 | + Retrieves a structured task and waits for it to finish. |
| 46 | + """ |
| 47 | + |
| 48 | + print("Retrieving structured task...") |
| 49 | + |
| 50 | + # Structured Output |
| 51 | + class HackerNewsPost(BaseModel): |
| 52 | + title: str |
| 53 | + url: str |
| 54 | + |
| 55 | + class SearchResult(BaseModel): |
| 56 | + posts: List[HackerNewsPost] |
| 57 | + |
| 58 | + structured_task = await client.tasks.create_task( |
| 59 | + task=""" |
| 60 | + Find top 10 Hacker News articles and return the title and url. |
| 61 | + """, |
| 62 | + llm="gpt-4.1", |
| 63 | + schema=SearchResult, |
| 64 | + ) |
| 65 | + |
| 66 | + print(f"Structured Task ID: {structured_task.id}") |
| 67 | + |
| 68 | + while True: |
| 69 | + structured_status = await client.tasks.retrieve(task_id=structured_task.id, schema=SearchResult) |
| 70 | + print(f"Structured Task Status: {structured_status.status}") |
| 71 | + |
| 72 | + if structured_status.status == "finished": |
| 73 | + if structured_status.parsed_output is None: |
| 74 | + print("Structured Task No output") |
| 75 | + else: |
| 76 | + for post in structured_status.parsed_output.posts: |
| 77 | + print(f" - {post.title} - {post.url}") |
| 78 | + |
| 79 | + break |
| 80 | + |
| 81 | + await asyncio.sleep(1) |
| 82 | + |
| 83 | + print("Done") |
| 84 | + |
| 85 | + |
| 86 | +# Main |
| 87 | + |
| 88 | + |
| 89 | +async def main() -> None: |
| 90 | + await asyncio.gather( |
| 91 | + # |
| 92 | + retrieve_regular_task(), |
| 93 | + retrieve_structured_task(), |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +asyncio.run(main()) |
0 commit comments