# Suno Alexa Music Skill

## 1. Project Overview

Integration enabling users to create and play Suno-generated music through Alexa devices. The skill uses Alexa's Music Skill API and Alexa+ generative AI capabilities to allow real-time music creation via voice commands.

**Key Features:**
- Real-time song generation via voice commands
- Standard playback controls (pause, resume, next, previous)
- Personal playlist support (2500 entity limit per user)
- Account linking via OAuth 2.0

**Customer Flow:** User says "create a rock song about space" → Alexa processes request via our Lambda → Suno generates music in real-time → User hears creation with displayed lyrics.

## 2. System Architecture

```mermaid
flowchart TD
    User([User])
    AlexaDevice[Alexa Device]
    AlexaService[Alexa Service]
    Lambda[Lambda<br>us-east-1]
    StudioAPI[studio-api.prod.suno.com]
    %% RDS[(RDS DB)]
    CloudFront[CloudFront CDN]
    S3[(AWS S3)]
    
    subgraph Modal["Modal"]
        direction TB
        Orchestrator[Orchestrator]
        Engine[Engine]
        SDXL[SDXL]
        ModalQueue[Modal Queue]
        AudioPipe[audiopipe.suno.ai]
    end
    
    %% User interaction flow
    User <-->|Voice/Audio| AlexaDevice
    AlexaDevice <-->|Commands/TTS| AlexaService
    AlexaService <-->|API Requests| Lambda
    Lambda <-->|API Requests| StudioAPI
    
    %% Song generation flow
    Engine -->|Push chunk| ModalQueue
    StudioAPI -->|Generate Clip| Orchestrator
    %% Orchestrator -->|Callback| StudioAPI
    Orchestrator --> Engine
    Orchestrator --> SDXL
    
    %% Audio streaming path
    Orchestrator -->|Push lyrics tokens| ModalQueue
    Orchestrator -->|Upload lyrics| S3
    AudioPipe -->|Read audio chunks<br>and lyrics tokens| ModalQueue
    Lambda -.->|SSE stream for song title| AudioPipe
    AlexaDevice -.->|Direct Audio Stream| AudioPipe
    
    %% Cover art path
    SDXL -->|Upload image| S3
    Engine -->|Upload audio| S3
    AlexaDevice -.->|Lyrics, Cover Art<br/>and full-song MP3s<br/>using signed URLs| CloudFront
    S3 -->|Origin| CloudFront
    
    %% Database updates
    %% StudioAPI <-->|Update Clip Metadata| RDS
    
    classDef amazon fill:#00CAFF,stroke:#232F3E,stroke-width:1px,color:black;
    classDef suno fill:#9370DB,stroke:#4B0082,stroke-width:1px,color:white;
    classDef user fill:#E6E6FA,stroke:#483D8B,stroke-width:1px,color:black;
    classDef aws fill:#FF9900,stroke:#232F3E,stroke-width:1px,color:black;
    classDef cf fill:#FF9900,stroke:#232F3E,stroke-width:1px,color:black;
    classDef modal fill:#33333366,stroke:#00AA44,stroke-width:2px,color:white;
    
    class AlexaDevice,AlexaService amazon;
    class StudioAPI suno;
    class User user;
    class Lambda suno;
    class S3,RDS aws;
    class CloudFront cf;
    class Modal,Orchestrator,Engine,SDXL,ModalQueue,AudioPipe modal;
```

## 3. Key Components

### 3.1 Alexa Components

**Alexa Device:**
- Captures and sends voice to Alexa Service
- Renders TTS responses ("Creating a song for you...")
- Directly fetches audio from Suno (no proxy)
- Renders lyrics and artwork on Now Playing Screen (NPS)

**Alexa Service:**
- Processes voice into intents
- Manages OAuth tokens (refresh handled automatically)
- Routes requests to appropriate Lambda functions

### 3.2 Lambda Function

Stateless request processor handling Alexa's API calls:
- Primary lambda function must be located in us-east-1
- Trigger validates request authenticity from Alexa service

### 3.3 Suno Service

**Music Generation:**
- GPC3.0 NL query → Check Entitlements → Generate and Moderate Lyrics → Audio Generation and Streaming
- Title extraction for early return when generating lyrics

**Audio Streaming:**
- Direct HTTP streaming to Alexa devices
- Signed URLs for security
- Format: [STREAM FORMAT SPEC - TBD]

**Resource Management:**
- WebVTT lyrics (with/without timestamps)
- Cover art generation
- Metadata fields
- Suno Playlist <-> Alexa personal catalog syncing

## 4. Key Workflows

### 4.1 Song Creation Flow

```mermaid
sequenceDiagram
    # autonumber
    actor User
    participant Device as Alexa Device
    participant Service as Alexa Service
    participant Lambda as Lambda
    participant Suno as Suno
    
    User->>Device: "create a song about space"
    activate Device
    Device->>Service: Voice command
    activate Service
    
    critical 5s timeout
      Service->>Lambda: GetPlayableContent
      activate Lambda
      Service->>Device: TTS directive
      Device->>User: "Creating a song for you…"
      Lambda->>Suno: Generate Clip
      activate Suno
      Suno->>Lambda: Return title
      Lambda->>Service: Clip ID and Title
    end
    
    critical 5s timeout
      Service->>Lambda: Initiate
      Lambda->>Suno: Fetch clip resources
      Suno->>Lambda: Return available resources
      Lambda->>Service: URIs (lyrics, image, stream)
      deactivate Lambda
    end
    
    Service->>Device: Playback directive with URIs
    deactivate Service
    
    Device->>Suno: Direct audio stream request
    Suno-->>Device: Stream audio content
    Device->>User: Audio playback<br>with Lyrics Display
    deactivate Device
    
    Suno->>Suno: Finish clip generation
    deactivate Suno
```

### 4.2 OAuth Authorization Flow

Based on OAuth 2.0 authorization code flow with Alexa-specific requirements:

1. Partner redirects to `/api/v2/external/oauth/authorize` with client_id, redirect_uri, etc.
2. Frontend handles authentication and consent
3. Backend generates authorization code
4. Redirect to partner with code
5. Partner exchanges code for access/refresh tokens
6. Alexa manages token refresh (180-day requirement)

```python
# OAuth configuration snippet
OAUTH2_PROVIDER = {
    'SCOPES': {
        'read_profile': 'Read user profile information',
        'generate_music': 'Generate music with Suno',
        'read_music': 'Access user music library',
    },
    'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,  # 1 hour
    'REFRESH_TOKEN_EXPIRE_SECONDS': 15552000,  # 180 days (Alexa requirement)
    'REFRESH_TOKEN_GRACE_PERIOD_SECONDS': 30,
    'OAUTH2_VALIDATOR_CLASS': 'studio_api.bots.oauth.validators.SunoOAuth2Validator',
    'AUTHORIZATION_CODE_EXPIRE_SECONDS': 600,  # 10 minutes
    "PKCE_REQUIRED": False,  # Alexa does not support PKCE
}
```

## 5. Integration Points

### 5.1 Alexa Music Skill API

**GetPlayableContent 3.0:**
- Handles NL_QUERY for song creation
- Returns song title within 5s
- [IMPLEMENTATION DETAILS - TBD]

**Initiate API:**
- Returns URLs for lyrics (WebVTT), cover art, audio stream
- Must complete within 5s
- [IMPLEMENTATION DETAILS - TBD]

**GetDisplayableContent:**
- Play queue/recommendations displayed on Now Playing Screen. 
- Uses syncToken/correlationToken for syncing catalog with Suno playlist. 
- [IMPLEMENTATION DETAILS - TBD]

### 5.2 OAuth Endpoints

| Endpoint | Purpose | Notes |
|----------|---------|-------|
| `/api/v2/external/oauth/authorize` | Start OAuth flow | Redirects to frontend |
| `/api/v2/external/oauth/token` | Exchange code for tokens | Requires client_secret |
| `/api/v2/external/oauth/generate-code` | Generate auth code | Internal endpoint |
| `/api/v2/external/oauth/client-info` | Fetch app details | For consent screen |
| `/api/v2/external/oauth/generate` | Protected resource | Requires access_token |

### 5.3 Account Linking

Alexa requires account linking for music skills. Key requirements:

- OAuth 2.0 authorization code flow
- 180-day refresh token expiration
- No PKCE support
- Token refresh handled by Alexa service

**Alexa Console Configuration:**
- Redirect URIs: `https://pitangui.amazon.com/api/skill/link/M211LAR57QLT8O` and regional variants
- Client ID/Secret from management command
- Required scopes: `read_profile read_music generate_music`

### 5.4 Lyrics and Media Content

**WebVTT Format:**
```
WEBVTT

00:00:01.000 --> 00:00:05.000
First line of lyrics

00:00:05.500 --> 00:00:10.000
Second line of lyrics
```

- Non-timestamped lyrics use same format without timestamps
- Current latency: P95 11.8s, P99 18.6s (too slow!)
- Constant-speed scrolling fallback for non-timestamped lyrics

**URL Signing:**
- All resource URLs must be signed
- [IMPLEMENTATION DETAILS - TBD]

## 6. Setup & Configuration

### 6.1 Development Environment

**Prerequisites:**
- AWS CLI configured for Lambda deployment
- Ask CLI configured for Skill Manifest updating
- [OTHER PREREQUISITES - TBD]

### 6.2 OAuth Client Creation

```bash
uv run manage.py create_oauth_client \
    --name "Alexa Music Skill" \
    --redirect-uris "https://pitangui.amazon.com/api/skill/link/M211LAR57QLT8O https://alexa.amazon.co.jp/api/skill/link/M211LAR57QLT8O https://layla.amazon.com/api/skill/link/M211LAR57QLT8O" \
    --scopes "read_profile read_music generate_music" \
    --pkce "disabled"
```

### 6.4 Alexa Skill Configuration

**Skill Manifest:**
- [MANIFEST DETAILS - TBD]

**Account Linking Setup:**
- [SETUP DETAILS - TBD]

## 7. Testing

### 7.1 Local Testing

**Test Request Templates:**
<details>
<summary>GetPlayableContent</summary>

```jsonc
{
    "header": {
        "messageId": "UF8XXr2bvC6f8VcQ6LSHeVvCP",
        "namespace": "Alexa.Media.Search",
        "name": "GetPlayableContent",
        "payloadVersion": "1.0"
    },
    "payload": {
        "requestContext": {
            "user": {
                "id": "amzn1.ask.account.AMA4FTMYVCLWXP7NTUIM3CQ66BHPZPX2P6CG6LN3KFXVGZG4GM37746JPQXQWZBM7LZQA76AD4MM5M5ZDY56TWYN6NMVD4NWOFOC6YWVDSHHL43STCG7Y7QWR7PSI45VE7OZUWEUXCJPMJGFKLSD364TF5UHMOSQZ6LKUSDGVOLFCT6GV2WO6BMRL452MDR4FARKCB7SUYYUFEDXP7WL7C4Y4OQRX4YYSF5B5VPU3U",
                "accessToken": null
            },
            "location": {
                "originatingLocale": "en-US",
                "countryCode": "US"
            },
            "advertising": {
                "limitAdTracking": true,
                "advertisingId": "00000000-0000-0000-0000-000000000000"
            },
            "apiAccessToken": null,
            "apiEndpoint": null
        },
        "filters": {
            "explicitLanguageAllowed": true
        },
        "policies": null,
        "experience": null,
        "selectionCriteria": {
            "attributes": [
                {
                    "type": "MEDIA_TYPE",
                    "value": "TRACK"
                }
            ]
        }
    }
}
```
</details>

More examples - TBD

### 7.2 Alexa Developer Console

For skill testing, use the Alexa Developer Console:
- Skill testing tab
- CloudWatch logs (Lambda)
- [ACCESS DETAILS - TBD]

### 7.3 Performance Testing

**Critical Metrics:**
- GetPlayableContent response time (must be <5s)
- Initiate response time (must be <5s)
- Lyrics generation time (target: <10s)

**Test Plan:**
- [TEST PLAN DETAILS - TBD]

### 7.4 Common Test Cases

- Song creation with various genres/prompts
- OAuth flow with new/existing users
- Error cases:
  - Timeout handling
  - Invalid tokens
  - Network interruptions

## 8. Resources & References

- [Alexa Skills Kit](https://developer.amazon.com/en-US/docs/alexa/ask-overviews/what-is-the-alexa-skills-kit.html)
- [The Music, Raio, Podcast Skill API](https://developer.amazon.com/en-US/docs/alexa/music-skills/api-reference-overview.html)


