System Architecture
Galactic Radio MusicGen — How It All Works
Complete technical reference. Covers the full stack: music generation pipeline, A2A protocol, authentication, API key management, CLI, and deployment.
System Architecture
High-level architecture and how each layer connects
Galactic Radio MusicGen is a production FastAPI service that generates AI music using Google's Lyria 3 API. It supports full songs and jingles, serves Web, CLI, and AI Agent clients simultaneously.
Music Generation Pipeline
How a song goes from request to playback-ready audio in 6 steps
Input Received
User submits title, genre, mood, lyrics, instruments, BPM, key/scale. User credit is deducted (1 per song).
POST /api/v1/songs/generate
Prompt Assembly
MusicGenService.build_prompt() assembles a structured prompt from all parameters.
Lyria 3 API Call
Sends prompt to Google's Lyria 3 API via google-genai SDK. Returns MP3 audio bytes + generated lyrics.
Audio Processing
Reads MP3 duration via Mutagen. Records file size and format metadata.
audio_utils.get_mp3_duration()
Upload to GCS
Audio uploaded to Google Cloud Storage at songs/{uid}/{song_id}/song.mp3. Public URL generated.
StorageService.upload_audio()
Record Complete
Song record updated in Firestore with status=completed, audio_url, duration. Credits deducted from user.
Authentication
Three auth methods serving different client types
Firebase JWT
Google Sign-In via Firebase Auth SDK. Frontend sends Firebase ID token as Bearer. Uses shared grn-weather-auth-only project.
User API Key
User API keys prefixed grm_. Sent via X-API-Key header. SHA-256 hashed, stored in Firestore. Supports naming, expiry, revocation.
Service API Keys
For service-to-service communication. Configured in SERVICE_API_KEYS env var. Grants SERVICE role with full access.
require_admin() dependency. Local dev bypasses auth entirely with ADMIN role.
Credit System
User-scoped credits for music generation
1 credit = 1 song generation (full song or jingle). New users start with 3 credits. Credits are deducted before generation begins. If generation fails, credits are NOT automatically refunded (the attempt still consumed API resources). Checking song status or listing songs is free.
/api/v1/credits/purchase endpoint exists as a placeholder for AP2 payment integration. Currently returns payment_required status.
A2A Protocol (Agent-to-Agent)
Google's open protocol for AI agents to discover and use the music generation service
The A2A layer runs alongside the existing REST API. Any A2A-compatible agent can discover the service via the Agent Card, then interact using JSON-RPC messages.
Agent Skills
JSON-RPC Methods
| Method | Description |
|---|---|
tasks/send | Send a task to the agent, returns result |
API Key Management
Full lifecycle management for user API keys
API keys use a dual-field architecture: api_keys (array of hashes for fast array-contains lookups) and api_key_details (map of hash→metadata). Keys support naming, expiration dates, and soft revocation.
Key Lifecycle
Create
Generate grm_xxx key, SHA-256 hash stored in Firestore. Metadata: name, prefix, created_at, expires_at. Raw key shown once.
Use
Agent/CLI sends X-API-Key header. Backend hashes, looks up via array-contains, checks revoked_at and expires_at.
Revoke
Soft-revoke sets revoked_at timestamp. Key stays in list but auth is denied. Can't be undone.
Delete
Hard-delete removes from both api_keys array and api_key_details map. Permanent.
API Reference
REST endpoints and their purpose
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| Health & System | |||
| GET | /api/v1/health | Health check | None |
| GET | /api/v1/info | Service info | None |
| Users & Auth | |||
| POST | /api/v1/users/register | Register with email/password | None |
| POST | /api/v1/users/oauth-signin | OAuth sign-in (auto-provisions) | Firebase |
| GET | /api/v1/users/me | Get current profile | Required |
| PATCH | /api/v1/users/me | Update profile | Required |
| POST | /api/v1/users/me/avatar | Upload avatar | Required |
| GET | /api/v1/users/me/stats | Get play stats | Required |
| API Keys | |||
| POST | /api/v1/users/api-keys | Create API key | Required |
| GET | /api/v1/users/api-keys | List API keys | Required |
| PATCH | /api/v1/users/api-keys/{key_id} | Update key metadata | Required |
| POST | /api/v1/users/api-keys/{key_id}/revoke | Revoke key | Required |
| DELETE | /api/v1/users/api-keys/{key_id} | Delete key | Required |
| Songs | |||
| POST | /api/v1/songs/generate | Generate a song | Required |
| GET | /api/v1/songs | List/search songs | Required |
| GET | /api/v1/songs/{song_id} | Get song details | Required |
| PATCH | /api/v1/songs/{song_id} | Update song metadata | Required |
| POST | /api/v1/songs/{song_id}/art | Upload cover art | Required |
| POST | /api/v1/songs/{song_id}/play | Record play event | Required |
| DELETE | /api/v1/songs/{song_id} | Delete song | Required |
| Credits | |||
| GET | /api/v1/credits/balance | Get credit balance | Required |
| POST | /api/v1/credits/purchase | Purchase credits (placeholder) | Required |
| Configuration (Admin) | |||
| GET | /api/v1/config | Get runtime config | Admin |
| PATCH | /api/v1/config | Update config | Admin |
| A2A Protocol | |||
| GET | /.well-known/agent.json | Agent Card discovery | None |
| POST | /a2a | A2A JSON-RPC endpoint | Required |
CLI Tool (galactic-musicgen)
Command-line interface for power users and automation
Install: pip install -e . — then use galactic-musicgen from the terminal.
Song Management
galactic-musicgen generate --title "Cosmic Dawn" --genre ambient --mood ethereal
Generate a song
galactic-musicgen list [--mine] [--limit 20]
List songs
galactic-musicgen get <song_id>
Get song details
galactic-musicgen edit <song_id> --title "New Title"
Edit metadata
galactic-musicgen delete <song_id>
Delete a song
galactic-musicgen play <song_id> --location "web-player"
Record play
API Key Management
galactic-musicgen keys list
List all API keys
galactic-musicgen keys create --name "My Agent" --expires 2026-12-31
Create named key
galactic-musicgen keys revoke <key_id>
Revoke a key
galactic-musicgen keys delete <key_id>
Delete a key permanently
Deployment
Cloud Build, Docker, and Cloud Run configuration
Key Environment Variables
ENVIRONMENT=production GCP_PROJECT_ID=gen-lang-client-0957930691 GCS_BUCKET_NAME=galactic-radio-musicgen-audio GOOGLE_API_KEY=*** FIREBASE_PROJECT_ID=gen-lang-client-0957930691 FIREBASE_AUTH_PROJECT_ID=grn-weather-auth-only SERVICE_API_KEYS=*** RATE_LIMIT_PER_MINUTE=60
--set-env-vars flag replaces ALL env vars on deploy. All env vars must be in cloudbuild.yaml or they'll be wiped.
Tech Stack
Every tool and service in the system
Backend
AI / Music
Google Cloud
Audio
Protocols
Dev & CLI
Project Structure
galactic-radio-musicgen/
src/galactic_musicgen/
app.py # FastAPI application factory
config.py # Pydantic settings from env vars
dependencies.py # ServiceContainer (all singletons)
middleware.py # Rate limiting, CORS, security headers
exceptions.py # Error handlers
auth/
firebase.py # Firebase token verification
api_key.py # API key validation + revocation checks
dependencies.py # get_current_user, require_admin
api/v1/
router.py # REST endpoint registration
users.py # /users/me, /users/api-keys, /oauth-signin
songs.py # /songs/generate, CRUD, play tracking
credits.py # /credits/balance, /credits/purchase
config.py # /config (admin)
health.py # /health, /info
a2a/
agent_card.py # Agent Card with skills
handler.py # JSON-RPC 2.0 handler
router.py # Mount A2A routes
services/
music_gen.py # Lyria 3 API wrapper
storage.py # GCS upload/download
audio_utils.py # MP3 duration detection (Mutagen)
models/
domain.py # AuthenticatedUser, User, Song
enums.py # UserRole, SongStatus, GenerationType
requests.py # API request models
responses.py # API response models
repositories/
user_repo.py # Firestore user CRUD + API keys
song_repo.py # Firestore song CRUD + search
frontend/
router.py # Serve static HTML pages
static/ # HTML, CSS, JS, favicon
tests/
unit/ # Unit tests
integration/ # Integration tests
Dockerfile # python:3.12-slim
cloudbuild.yaml # Cloud Build -> Cloud Run deploy
pyproject.toml # Project metadata + deps