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