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

# Quickstart (Python SDK)

> Get started with ABV tracing in your Python application in under 5 minutes

<Tip>
  If you're creating a new ABV account, the onboarding flow will guide you through these steps automatically. This guide is for manual setup or reference.
</Tip>

<Steps>
  <Step title="Get your API key" icon="key">
    Create an ABV account and generate API credentials:

    1. [Sign up for ABV](https://app.abv.dev/auth/sign-up) (free trial available)
    2. Navigate to **Project Settings** → **API Keys**
    3. Click **Create API Key** and copy your key (starts with `sk-abv-...`)
  </Step>

  <Step title="Install the ABV SDK" icon="download">
    Install the required packages for ABV tracing:

    ```bash theme={null}
    pip install abvdev python-dotenv
    ```

    This installs:

    * `abvdev` - ABV's Python SDK for tracing and observability
    * `python-dotenv` - Environment variable management from `.env` files
  </Step>

  <Step title="Configure environment variables" icon="gear">
    Create a `.env` file in your project root with your ABV credentials:

    ```bash title=".env" theme={null}
    ABV_API_KEY="sk-abv-..."
    ABV_HOST="https://app.abv.dev"  # US region
    # ABV_HOST="https://eu.app.abv.dev"  # EU region (uncomment if needed)
    ```

    <Warning>
      Make sure `.env` is in your `.gitignore` to avoid committing secrets.
    </Warning>
  </Step>
</Steps>

# Choose Your Instrumentation Method

ABV's Python SDK offers multiple ways to create traces. Choose based on your use case:

<Tabs>
  <Tab title="Gateway Auto-Tracing" icon="route">
    **Best for**: LLM applications that need automatic tracing with zero manual instrumentation

    The ABV Gateway is the fastest way to get complete observability for LLM calls. It automatically captures all metrics without any manual tracing code.

    <Tip>
      New users get \$1 in free credits to test the gateway.
    </Tip>

    ```python theme={null}
    from dotenv import load_dotenv
    from abvdev import ABV

    # Load environment variables
    load_dotenv()

    # Initialize the ABV client
    abv = ABV()  # Uses ABV_API_KEY from environment

    # Make a gateway request - automatically creates a complete trace
    response = abv.gateway.chat.completions.create(
        provider='openai',
        model='gpt-4o-mini',
        messages=[
            {'role': 'user', 'content': 'What is the capital of France?'}
        ]
    )

    # Access the response
    output = response['choices'][0]['message']['content']
    print(f"Response: {output}")
    ```

    **What gets captured automatically:**

    * Full conversation context (user query and LLM response)
    * Model and provider information
    * Token usage (input/output counts)
    * Cost tracking (deducted from gateway credits)
    * Latency metrics (total duration and API timing)

    **Switch providers easily:**

    ```python theme={null}
    # Try Anthropic's Claude
    response = abv.gateway.chat.completions.create(
        provider='anthropic',
        model='claude-sonnet-4-5',
        messages=[{'role': 'user', 'content': 'What is the capital of France?'}]
    )

    # Or try Google's Gemini
    response = abv.gateway.chat.completions.create(
        provider='gemini',
        model='gemini-2.0-flash-exp',
        messages=[{'role': 'user', 'content': 'What is the capital of France?'}]
    )
    ```

    <Info>
      The gateway requires no additional setup beyond installing `abvdev`. It automatically handles tracing, cost tracking, and provider switching.
    </Info>
  </Tab>

  <Tab title="@observe Decorator" icon="at">
    **Best for**: Simple functions where you want automatic instrumentation

    The `@observe` decorator is the easiest way to add tracing. It automatically captures function name, arguments, return value, and timing.

    ```python theme={null}
    from dotenv import load_dotenv
    from abvdev import observe, get_client

    # Load environment variables
    load_dotenv()

    @observe
    def my_function():
        # Function logic here
        return "Hello, world!"

    # Call the function - it's automatically traced
    my_function()

    # Flush events in short-lived applications
    abv = get_client()
    abv.flush()
    ```

    **What gets captured:**

    * Function name and arguments
    * Return value
    * Execution time
    * Any exceptions raised

    <Tip>
      The `@observe` decorator is perfect for quick instrumentation. Just add it to any function you want to trace!
    </Tip>
  </Tab>

  <Tab title="Context Managers" icon="brackets-curly">
    **Best for**: Fine-grained control over what you track and when

    Context managers give you more control over instrumentation. They're ideal for complex workflows where you need to track specific operations.

    ```python theme={null}
    from dotenv import load_dotenv
    from abvdev import get_client

    load_dotenv()
    abv = get_client()

    # Create a parent span for the entire request
    with abv.start_as_current_span(name="process-request") as span:
        span.update(input={"query": "What is the capital of France?"})

        # Create a nested generation for an LLM call
        with abv.start_as_current_observation(
            as_type='generation',
            name="llm-call",
            model="gpt-4o"
        ) as generation:
            # Simulate LLM response
            generation.update(output="The capital of France is Paris.")

        span.update(output="Processing complete")

    # Flush events in short-lived applications
    abv.flush()
    ```

    **Key benefits:**

    * Explicit control over what's tracked
    * Easy nesting of observations
    * Update metadata at any point
    * Automatic cleanup when context exits

    <Note>
      Context managers automatically close spans when exiting the `with` block, preventing memory leaks and ensuring data is sent to ABV.
    </Note>
  </Tab>
</Tabs>

## Run Your First Trace

Execute your Python script to send your first trace to ABV:

```bash theme={null}
python your_script.py
```

Navigate to [app.abv.dev](https://app.abv.dev) and click **Traces** in the sidebar. You should see your trace with:

* The function/span name
* Input and output data
* Nested observation hierarchy (if using context managers or gateway)
* Timing information and metrics

<Tip>
  If you don't see traces immediately, wait a few seconds and refresh. Make sure you called `abv.flush()` for short-lived scripts (not needed for gateway requests).
</Tip>

# When to Use `flush()`

<Info>
  The `abv.flush()` call is only needed for **short-lived scripts** that exit immediately. Long-running applications (web servers, background workers) don't need it.
</Info>

**Use `flush()` for:**

* CLI scripts
* Batch processing jobs
* One-off tasks

**Don't use `flush()` for:**

* FastAPI/Flask web applications
* Django applications
* Long-running services

# Next Steps

## Enhance Your Traces

<CardGroup cols={2}>
  <Card title="Add metadata and tags" icon="tags" href="/developer/basic-features/metadata">
    Attach business context to traces for filtering and analysis
  </Card>

  <Card title="Track users and sessions" icon="users" href="/developer/basic-features/sessions">
    Group related traces by user journey or conversation
  </Card>

  <Card title="Monitor costs" icon="dollar-sign" href="/developer/basic-features/cost-tracking-implementation">
    Track LLM spending by user, feature, or model
  </Card>

  <Card title="Store and version datasets" icon="database" href="/developer/evaluations/datasets">
    Manage test datasets and examples for evaluations
  </Card>
</CardGroup>

## Build Production-Grade AI

<CardGroup cols={2}>
  <Card title="Set up guardrails" icon="shield" href="/developer/guardrails/overview">
    Add safety checks, PII detection, and content moderation
  </Card>

  <Card title="Run evaluations" icon="chart-line" href="/developer/evaluations/overview">
    Measure quality with automated LLM-as-judge evaluations
  </Card>

  <Card title="Manage prompts" icon="file-lines" href="/developer/prompt-management/overview">
    Version and deploy prompts without code changes
  </Card>

  <Card title="Access via API" icon="code" href="/developer/platform/api-data-platform/overview">
    Query traces, datasets, and metrics programmatically
  </Card>
</CardGroup>

## Advanced Platform Features

<CardGroup cols={2}>
  <Card title="Analyze metrics" icon="chart-bar" href="/developer/platform/metrics/overview">
    Track performance trends and usage patterns
  </Card>

  <Card title="Explore the SDK" icon="book" href="/developer/sdks/python/overview">
    Learn advanced SDK features and configuration options
  </Card>

  <Card title="Use the LLM Gateway" icon="route" href="/developer/llm-gateway/overview">
    Switch between LLM providers with automatic tracing
  </Card>

  <Card title="Manage team access" icon="users-gear" href="/developer/platform/administration/role-based-access-controls">
    Configure role-based access controls for your team
  </Card>
</CardGroup>
