> ## Documentation Index
> Fetch the complete documentation index at: https://docs.altrina.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> Get started with the Altrina Python SDK in 5 minutes

## Your First Automation

Let's run your first browser automation in just a few lines of code.

<Steps>
  <Step title="Install the SDK">
    ```bash theme={null}
    pip install altrina_sdk
    ```
  </Step>

  <Step title="Get Your API Key">
    Get your API key from [app.altrina.com/settings](https://app.altrina.com/settings)
  </Step>

  <Step title="Run Your First Task">
    ```python quickstart.py theme={null}
    from altrina_sdk import BrowserAgent

    # Create an agent with your API key
    agent = BrowserAgent("YOUR_API_KEY")

    # Run a simple task
    result = agent.run("Go to example.com and extract the main heading")

    # Print the result
    print(result.output)
    ```
  </Step>
</Steps>

That's it! You've just automated your first browser task. 🎉

## Understanding the Result

When you run a task, you get back a `JobResult` object with useful information:

```python theme={null}
result = agent.run("Your task here")

# Check if successful
if result.is_successful:
    print(f"✅ Success! Output: {result.output}")
    print(f"Credits used: {result.credits_used}")
else:
    print(f"❌ Failed: {result.error}")
```

## Common Use Cases

### 1. Extract Data from a Website

```python theme={null}
from altrina_sdk import BrowserAgent

agent = BrowserAgent("YOUR_API_KEY")

# Extract specific data
result = agent.extract(
    url="https://news.ycombinator.com",
    data_description="titles and points of the top 5 stories"
)

print(result.output)
```

### 2. Fill and Submit Forms

```python theme={null}
# Fill a contact form
result = agent.fill_form(
    url="https://example.com/contact",
    form_data={
        "name": "John Doe",
        "email": "john@example.com",
        "message": "Hello, I'm interested in your services"
    }
)

print("Form submitted!" if result.is_successful else f"Error: {result.error}")
```

### 3. Search and Extract Results

```python theme={null}
# Search and extract data
result = agent.search_and_extract(
    query="Python tutorials",
    num_results=10,
    data_description="title, URL, and description"
)

for item in result.output:
    print(f"- {item['title']}: {item['url']}")
```

### 4. Multi-Step Workflows

```python theme={null}
# Complex multi-step task
result = 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.output
for product in products:
    print(f"{product['name']}: ${product['price']} ({product['rating']} stars)")
```

## Monitoring Your Tasks

### Watch Live Execution

When you need to see what's happening:

```python theme={null}
from altrina_sdk import AltrinaClient

with 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}")
```

### Check Job Status

Monitor long-running tasks:

```python theme={null}
# Start a long task
job = client.run_browser_agent("Complex multi-page scraping task...")

# Check status periodically
import time
while 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
```

## Error Handling

Always handle potential errors gracefully:

```python theme={null}
from altrina_sdk import BrowserAgent
from altrina.exceptions import AuthenticationError, RateLimitError, TimeoutError

agent = 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}")
```

## Configuration Options

Customize browser behavior for your needs:

```python theme={null}
from altrina_sdk import BrowserAgent

agent = BrowserAgent(
    api_key="YOUR_API_KEY",
    residential_ip=True,           # Use residential proxy
    viewport_width=1920,           # Browser width
    viewport_height=1080,          # Browser height
    max_duration_minutes=10,       # Maximum task duration
    model="claude-sonnet-4-20250514",  # AI model to use
    verbose=True                   # Print progress updates
)

result = agent.run("Your task here")
```

## Working with Different Data Formats

The SDK automatically structures extracted data:

```python theme={null}
# Extract structured data
result = agent.extract(
    url="https://example-shop.com/products",
    data_description="product name, price, and availability as a list"
)

# Access as JSON
products = result.output  # Already parsed JSON

# Process the data
for product in products:
    if product.get("availability") == "in stock":
        print(f"{product['name']}: ${product['price']}")
```

## Async Operations (Advanced)

For concurrent tasks, use the async client:

```python theme={null}
import asyncio
from altrina_sdk import AsyncAltrinaClient

async 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 function
results = asyncio.run(scrape_multiple_sites())
```

## Best Practices

<AccordionGroup>
  <Accordion title="1. Use Clear, Specific Instructions">
    ```python theme={null}
    # ❌ Too vague
    result = agent.run("Get data from the website")

    # ✅ Clear and specific
    result = agent.run("""
        Go to example.com/products and extract:
        - Product names
        - Prices (including currency)
        - Stock status
        Format as a JSON list
    """)
    ```
  </Accordion>

  <Accordion title="2. Handle Rate Limits Gracefully">
    ```python theme={null}
    import time
    from altrina.exceptions import RateLimitError

    def 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
    ```
  </Accordion>

  <Accordion title="3. Use Context Managers">
    ```python theme={null}
    # Ensures proper cleanup
    with AltrinaClient("YOUR_API_KEY") as client:
        result = client.run_and_wait("Your task")
    # Resources automatically cleaned up
    ```
  </Accordion>

  <Accordion title="4. Monitor Credit Usage">
    ```python theme={null}
    result = agent.run("Your task")
    print(f"Credits used: {result.credits_used}")

    # Track total usage
    total_credits = 0
    for task in tasks:
        result = agent.run(task)
        total_credits += result.credits_used

    print(f"Total credits used: {total_credits}")
    ```
  </Accordion>
</AccordionGroup>

## Interactive Examples

Try these examples to see different capabilities:

<CodeGroup>
  ```python E-commerce theme={null}
  from altrina_sdk import BrowserAgent

  agent = 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']}")
  ```

  ```python News Aggregation theme={null}
  from altrina_sdk import BrowserAgent

  agent = BrowserAgent("YOUR_API_KEY")

  result = agent.run("""
      Visit these news sites and extract today's top headline from each:
      1. cnn.com
      2. bbc.com
      3. reuters.com
      Return as a list with source and headline.
  """)

  for news in result.output:
      print(f"{news['source']}: {news['headline']}")
  ```

  ```python Social Media theme={null}
  from altrina_sdk import BrowserAgent

  agent = BrowserAgent("YOUR_API_KEY", residential_ip=True)

  result = agent.run("""
      Go to twitter.com/OpenAI and extract:
      - The last 3 tweets
      - Number of likes and retweets for each
      - Tweet timestamps
  """)

  for tweet in result.output:
      print(f"{tweet['text'][:50]}... - {tweet['likes']} likes")
  ```
</CodeGroup>

## What's Next?

Now that you've mastered the basics:

<CardGroup cols={2}>
  <Card title="BrowserAgent API" icon="robot" href="/sdk/browser-agent">
    Explore all BrowserAgent methods
  </Card>

  <Card title="Advanced Examples" icon="code" href="/sdk/advanced-examples">
    See complex real-world examples
  </Card>

  <Card title="Error Handling" icon="shield-exclamation" href="/sdk/error-handling">
    Learn robust error handling
  </Card>

  <Card title="Async Client" icon="bolt" href="/sdk/async-client">
    Master concurrent operations
  </Card>
</CardGroup>

## Getting Help

* 📚 [Full API Reference](/sdk/browser-agent)
* 💬 [GitHub Discussions](https://github.com/GeneralAgencyAI/altrina_sdk/discussions)
* 📧 [Email Support](mailto:support@altrina.com)
