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

# Basic Usage Examples

> Learn the basics of using the Switchport Python SDK

## Overview

This guide demonstrates the fundamental operations of the Switchport SDK:

* Initializing the client
* Executing prompts
* Recording metrics
* Working with different metric types

## Setup

First, install the SDK and set your API key:

```bash theme={null}
pip install switchport
export SWITCHPORT_API_KEY=sp_your_key_here
```

## Example 1: Simple Prompt Execution

Execute a prompt without context or variables:

```python theme={null}
from switchport import Switchport

# Initialize client
client = Switchport()

# Execute prompt
response = client.prompts.execute(
    prompt_key="welcome-message"
)

print("Generated text:")
print(response.text)
print(f"\nModel: {response.model}")
print(f"Version: {response.version_name}")
```

## Example 2: Prompt with Variables

Pass dynamic variables to your prompt:

```python theme={null}
from switchport import Switchport

client = Switchport()

response = client.prompts.execute(
    prompt_key="welcome-message",
    variables={
        "customer_name": "Alice",
        "product": "Pro Plan"
    }
)

print("Generated text:")
print(response.text)
```

<Note>
  Make sure your prompt template in the dashboard includes the variables like `{{customer_name}}` and `{{product}}`.
</Note>

## Example 3: Prompt with Subject

Use subject for deterministic version assignment:

```python theme={null}
from switchport import Switchport

client = Switchport()

response = client.prompts.execute(
    prompt_key="product-description",
    subject={"user_id": "user_123", "tier": "premium"},
    variables={"product_name": "Enterprise Widget"}
)

print(f"Version: {response.version_name}")
print(f"Request ID: {response.request_id}")
print(f"\n{response.text}")
```

## Example 4: Recording a Float Metric

Track numerical values like satisfaction scores:

```python theme={null}
from switchport import Switchport

client = Switchport()

# Record user satisfaction (1-5 scale)
result = client.metrics.record(
    metric_key="user_satisfaction",
    value=4.5,
    subject={"user_id": "user_123"}
)

print(f"Metric recorded! Event ID: {result.metric_event_id}")
```

## Example 5: Recording a Boolean Metric

Track true/false events like conversions:

```python theme={null}
from switchport import Switchport

client = Switchport()

# Track conversion
result = client.metrics.record(
    metric_key="conversion_success",
    value=True,
    subject={"user_id": "user_123", "campaign": "summer_2025"}
)

print(f"Conversion tracked: {result.success}")
```

## Example 6: Recording an Enum Metric

Track categorical values like sentiment:

```python theme={null}
from switchport import Switchport

client = Switchport()

# Track user sentiment
result = client.metrics.record(
    metric_key="user_sentiment",
    value="positive",  # Could be "positive", "negative", "neutral"
    subject={"feature": "new_ui", "user_id": "user_123"}
)

print(f"Sentiment recorded: {result.metric_event_id}")
```

## Example 7: Complete Workflow

Execute a prompt and record metrics together:

```python theme={null}
from switchport import Switchport

client = Switchport()

# Step 1: Execute prompt with subject identification
response = client.prompts.execute(
    prompt_key="welcome-email",
    subject={"user_id": "user_123"},
    variables={"name": "Alice"}
)

# Step 2: Show/send the generated content
print(f"Generated email:\n{response.text}")

# Step 3: Simulate user interaction
# (In real app, this would happen when user actually interacts)
user_clicked = True
user_rating = 4.5

# Step 4: Record metrics with same subject
if user_clicked:
    client.metrics.record(
        metric_key="email_clicked",
        value=True,
        subject={"user_id": "user_123"}  # Same subject!
    )

client.metrics.record(
    metric_key="satisfaction",
    value=user_rating,
    subject={"user_id": "user_123"}  # Same subject!
)

print(f"\nMetrics recorded for version: {response.version_name}")
```

## Example 8: Multiple Users

See how different users might get different versions:

```python theme={null}
from switchport import Switchport

client = Switchport()

users = ["user_001", "user_002", "user_003", "user_004", "user_005"]

for user_id in users:
    response = client.prompts.execute(
        prompt_key="product-pitch",
        subject={"user_id": user_id},
        variables={"product": "Pro Plan"}
    )

    print(f"{user_id} got version: {response.version_name}")
```

Example output:

```
user_001 got version: v1
user_002 got version: v2
user_003 got version: v1
user_004 got version: v2
user_005 got version: v1
```

## Example 9: Response Time Tracking

Track how long operations take:

```python theme={null}
from switchport import Switchport
import time

client = Switchport()

start_time = time.time()

response = client.prompts.execute(
    prompt_key="complex-analysis",
    variables={"data": "large dataset..."}
)

end_time = time.time()
response_time_ms = (end_time - start_time) * 1000

# Record response time
client.metrics.record(
    metric_key="response_time_ms",
    value=response_time_ms,
    subject={"endpoint": "/api/analysis"}
)

print(f"Response time: {response_time_ms:.2f}ms")
```

## Example 10: String vs Dictionary Subject

Subject can be a simple string or a dictionary:

```python theme={null}
from switchport import Switchport

client = Switchport()

# Using string subject
response1 = client.prompts.execute(
    prompt_key="greeting",
    subject="guest_user"
)

# Using dictionary subject
response2 = client.prompts.execute(
    prompt_key="greeting",
    subject={
        "user_type": "premium",
        "region": "us-west",
        "tier": "gold"
    }
)

print(f"String subject version: {response1.version_name}")
print(f"Dict subject version: {response2.version_name}")
```

## Complete Example Script

Here's a complete script you can run:

```python theme={null}
"""
Basic Switchport SDK usage example.
Make sure to set SWITCHPORT_API_KEY environment variable.
"""

from switchport import Switchport

def main():
    # Initialize client
    client = Switchport()

    print("=" * 60)
    print("Switchport SDK - Basic Usage Example")
    print("=" * 60)

    # Execute a prompt
    print("\n1. Executing prompt...")
    try:
        response = client.prompts.execute(
            prompt_key="welcome-message",
            variables={"customer_name": "Alice"}
        )
        print(f"✓ Success!")
        print(f"  Generated: {response.text[:100]}...")
        print(f"  Version: {response.version_name}")
    except Exception as e:
        print(f"✗ Error: {e}")

    # Record a metric
    print("\n2. Recording metric...")
    try:
        result = client.metrics.record(
            metric_key="satisfaction",
            value=4.5,
            subject={"user_id": "user_123"}
        )
        print(f"✓ Success!")
        print(f"  Event ID: {result.metric_event_id}")
    except Exception as e:
        print(f"✗ Error: {e}")

    print("\n" + "=" * 60)
    print("Example completed!")
    print("=" * 60)

if __name__ == "__main__":
    main()
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Advanced Examples" icon="rocket" href="/sdk/python/examples/advanced-usage">
    Learn about A/B testing and advanced patterns
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/sdk/python/examples/error-handling">
    Learn how to handle errors gracefully
  </Card>
</CardGroup>
