from altrina_sdk import BrowserAgent# Create an agent with your API keyagent = BrowserAgent("YOUR_API_KEY")# Run a simple taskresult = agent.run("Go to example.com and extract the main heading")# Print the resultprint(result.output)
That’s it! You’ve just automated your first browser task. 🎉
from altrina_sdk import BrowserAgentagent = BrowserAgent("YOUR_API_KEY")# Extract specific dataresult = agent.extract( url="https://news.ycombinator.com", data_description="titles and points of the top 5 stories")print(result.output)
# Complex multi-step taskresult = agent.run(""" 1. Go to amazon.com 2. Search for 'wireless headphones' 3. Filter by 4+ star ratings 4. Sort by price (low to high) 5. Extract the first 5 products with name, price, and rating""")products = result.outputfor product in products: print(f"{product['name']}: ${product['price']} ({product['rating']} stars)")
from altrina_sdk import AltrinaClientwith AltrinaClient("YOUR_API_KEY") as client: # Start a job job = client.run_browser_agent( "Navigate to github.com and find trending Python repositories" ) # Get the live viewing URL print(f"🔴 Watch live: {job.live_url}") # Wait for completion result = job.wait_for_completion(verbose=True) print(f"Result: {result.output}")
# Start a long taskjob = client.run_browser_agent("Complex multi-page scraping task...")# Check status periodicallyimport timewhile True: status = job.get_status() print(f"Status: {status.status}") if status.status in ["completed", "failed"]: break time.sleep(5) # Wait 5 seconds before checking again
from altrina_sdk import BrowserAgentfrom altrina.exceptions import AuthenticationError, RateLimitError, TimeoutErroragent = BrowserAgent("YOUR_API_KEY")try: result = agent.run("Your task", timeout=60) # 60 second timeout print(result.output)except AuthenticationError: print("❌ Invalid API key. Get one at app.altrina.com/settings")except RateLimitError as e: print(f"⏳ Rate limited. Retry after {e.retry_after} seconds")except TimeoutError: print("⏱️ Task took too long. Try with a simpler directive")except Exception as e: print(f"Unexpected error: {e}")
# Extract structured dataresult = agent.extract( url="https://example-shop.com/products", data_description="product name, price, and availability as a list")# Access as JSONproducts = result.output # Already parsed JSON# Process the datafor product in products: if product.get("availability") == "in stock": print(f"{product['name']}: ${product['price']}")
import asynciofrom altrina_sdk import AsyncAltrinaClientasync def scrape_multiple_sites(): async with AsyncAltrinaClient("YOUR_API_KEY") as client: # Run multiple tasks concurrently tasks = [ client.run_browser_agent("Scrape site1.com for products"), client.run_browser_agent("Scrape site2.com for prices"), client.run_browser_agent("Scrape site3.com for reviews") ] jobs = await asyncio.gather(*tasks) # Wait for all to complete results = await asyncio.gather( *[job.wait_for_completion() for job in jobs] ) return results# Run the async functionresults = asyncio.run(scrape_multiple_sites())
# ❌ Too vagueresult = agent.run("Get data from the website")# ✅ Clear and specificresult = agent.run(""" Go to example.com/products and extract: - Product names - Prices (including currency) - Stock status Format as a JSON list""")
2. Handle Rate Limits Gracefully
import timefrom altrina.exceptions import RateLimitErrordef run_with_retry(agent, task, max_retries=3): for attempt in range(max_retries): try: return agent.run(task) except RateLimitError as e: if attempt < max_retries - 1: print(f"Rate limited. Waiting {e.retry_after}s...") time.sleep(e.retry_after) else: raise
3. Use Context Managers
# Ensures proper cleanupwith AltrinaClient("YOUR_API_KEY") as client: result = client.run_and_wait("Your task")# Resources automatically cleaned up
4. Monitor Credit Usage
result = agent.run("Your task")print(f"Credits used: {result.credits_used}")# Track total usagetotal_credits = 0for task in tasks: result = agent.run(task) total_credits += result.credits_usedprint(f"Total credits used: {total_credits}")
from altrina_sdk import BrowserAgentagent = BrowserAgent("YOUR_API_KEY")result = agent.run(""" Go to amazon.com and search for 'laptop'. Apply these filters: - Price: $500-$1000 - Brand: Dell or HP - Rating: 4 stars & up Extract the first 5 results with name, price, and rating.""")for laptop in result.output: print(f"{laptop['name']}: ${laptop['price']}")