{"slug": "designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms", "title": "Designing a Knowledge-Base Architecture for a Music App Powered by LLMs", "summary": "An engineer published an architecture design doc for an LLM-powered music app's knowledge layer, splitting it into three planes: a catalog graph of tracks, audio and rights data; per-user long- and short-term taste vectors projected into the model's context; and a RAG corpus of editorial and cultural knowledge used only for explanations. The design enforces a rule that the LLM proposes but the catalog disposes, so no track ID reaches the client unless the runtime verifies it exists, is licensed for the user's region, and matches parsed constraints. It targets five scenarios, from natural-language playlist generation and a conversational DJ to grounded music Q&A, cold-start discovery and creator tools.", "body_md": "A production-oriented architecture for turning \"something for a late-night drive, not too sad, a bit nostalgic\" into a real playlist — without hallucinating songs that don't exist.\n\nIf you've ever typed \"rainy city, neon, heartbeat, but not depressing\" into a music app and gotten back a playlist that feels like it was assembled by a committee, you already know the problem:\n\nMusic is multimodal, cultural, and vague. Tags like genre: indie or mood: chill collapse under the weight of how people actually describe what they want to hear.\n\nOver the last year, the teams shipping real LLM-powered music features (NetEase's Muse Mix, Spotify's AI DJ / podcast generation, YouTube Music's discovery surfaces) have converged on a similar shape: not a bigger model, but a knowledge layer around the model.\n\nThis post is an architecture design doc for that knowledge layer — written for engineers who have to ship it, not just demo it.\n\nBefore drawing boxes, here's what the app needs to do. Each scenario stresses the architecture differently.\n\nS1 Natural-language playlist generation \"45 min of focus music for coding at 2am, no vocals, slightly melancholic\" Parse mood/tempo/context, retrieve real tracks, explain choices\n\nS2 Conversational DJ \"Ok now make it more energetic but keep the same vibe\" Carry session context, mutate constraints, avoid whiplash\n\nS3 Music Q&A / artist knowledge \"Why does this song remind me of 2000s R&B?\" Grounded answer over catalog + editorial + web-free facts\n\nS4 Cold-start / new release discovery New user, new AI-generated track, no interactions Content understanding, not just collaborative filtering\n\nS5 Creator tools \"Write me a lo-fi loop in A minor at 85 BPM\" Generate, moderate, store under user, attach rights metadata\n\nThe key insight: S1–S4 are retrieval-and-grounding problems. S5 is a generation-and-lineage problem. Both need a knowledge base, but they need different shapes of it.\n\nClassic RAG assumes: documents → chunks → vectors → retrieve → generate. For a music catalog this breaks in three places:\n\nSo the knowledge base is not one vector index. It is a federated knowledge system with a strict rule:\n\nThe LLM proposes; the catalog disposes. No track ID reaches the client unless the runtime verified it exists, is licensed for this user's region, and matches the parsed constraints.\n\nPlane A — Catalog Knowledge (what exists)\n\n• Track / Album / Artist / Label entities in a graph (Neo4j or TigerGraph)\n\n• Audio-derived features: BPM, key, energy, danceability, timbre embeddings (CLAP / HTS-AT)\n\n• Text-derived features: lyrics embeddings, editorial tags, user-generated mood words\n\n• Rights & availability: territory, subscription tier, explicit-content flag\n\nPlane B — Taste Knowledge (what this user wants)\n\n• Long-term taste vector (updated nightly, from full history)\n\n• Short-term session vector (last ~20 events, in-memory)\n\n• Explicit signals: likes, dislikes, \"don't play this artist\", tempo preferences\n\n• Stored as soft tokens that get projected into the LLM's context at inference time — the same trick Spotify uses to personalize without retraining per user\n\nPlane C — World Knowledge (what music means)\n\n• Editorial articles, album reviews, artist bios, liner notes\n\n• Cultural associations: \"this was in Lost in Translation\", \"SoundCloud rap 2017\"\n\n• Stored as classic RAG chunks with provenance, used only for explanation and Q&A — never for track identity\n\nRule: Plane C can explain a recommendation, but it cannot originate one.\n\n┌──────────────────────────────────────────────────────────┐\n\n│  Client (iOS / Android / Web)                           │\n\n│  ├─ Player                                              │\n\n│  ├─ Conversation UI                                     │\n\n│  └─ On-device mini-index (top 5k recent tracks, HNSW)   │\n\n└──────────────┬───────────────────────────────────────────┘\n\n               │ HTTPS / WebSocket\n\n┌──────────────▼───────────────────────────────────────────┐\n\n│  API Gateway + Auth + Rate Limit                        │\n\n└──────────────┬───────────────────────────────────────────┘\n\n               │\n\n┌──────────────▼───────────────────────────────────────────┐\n\n│  Orchestrator (deterministic state graph)                │\n\n│  UNDERSTAND → PLAN → RETRIEVE → GROUND → RERANK → SAY   │\n\n│                                                          │\n\n│  (LLM calls only inside UNDERSTAND, PLAN, SAY)           │\n\n└──┬───────┬────────┬────────┬────────┬───────────────────┘\n\n   │       │        │        │        │\n\n┌──▼──┐ ┌─▼──┐ ┌───▼──┐ ┌──▼───┐ ┌─▼──────┐\n\n│Text │ │Audio│ │Collab│ │Graph │ │Editorial│\n\n│Vec  │ │Vec  │ │Index │ │Store │ │RAG     │\n\n│Idx  │ │Idx  │ │(CF)  │ │(KG)  │ │(Plane C)│\n\n└──┬──┘ └─┬──┘ └───┬──┘ └──┬───┘ └──┬─────┘\n\n   └──────┴────────┴───────┴────────┘\n\n                    │\n\n         ┌──────────▼──────────┐\n\n         │  Catalog Runtime    │  ← the only source of truth\n\n         │  (TrackID, rights,  │     for \"what can play\"\n\n         │   region, dislike)  │\n\n         └─────────────────────┘\n\nWhy a deterministic state graph, not a free-form agent?\n\nNetEase tried the ReAct-style loop first. It failed in production because intent-parsing errors compound across steps, and end-to-end success dropped below shipping threshold. Their fix — and ours — is a fixed 5–6 node graph where each failure mode has a named home you can swap without rewriting the controller.\n\nNode 1 — UNDERSTAND (LLM, structured output)\n\nInput: raw utterance + session context.\n\nOutput: strict JSON, no prose.\n\n{\n\n  \"mood\": [\"melancholic\", \"nostalgic\"],\n\n  \"energy\": [0.3, 0.55],\n\n  \"tempo_bpm\": [80, 110],\n\n  \"vocals\": \"any\",\n\n  \"context\": \"late_night_driving\",\n\n  \"avoid\": [\"heavy_metal\", \"explicit\"],\n\n  \"target_count\": 30,\n\n  \"max_per_artist\": 2,\n\n  \"time_range\": null,\n\n  \"language\": [\"en\", \"zh\"]\n\n}\n\nValidation is deterministic: out-of-range BPM? clamp. Unknown mood? drop. If JSON fails validation, retry once, then fall back to last-known-good intent.\n\nNode 2 — PLAN (small LLM or even a policy table)\n\nMaps intent → which retrievers to fire, with per-retriever k:\n\n• Semantic (text index): k=200\n\n• Audio-similarity (CLAP index): k=200\n\n• Collaborative (user-vector neighbors): k=150\n\n• Graph expansion (artist → similar artists → tracks): k=100\n\n• Editorial/scene index (curated \"late-night-driving\" shelves): k=50\n\nNode 3 — RETRIEVE (parallel, fan-out/fan-in)\n\nEach retriever returns (track_id, score, reason).\n\nMerge with Reciprocal Rank Fusion (simple, robust, beats learned fusion at small k):\n\ndef rrf(rank_lists, k=60):\n\n    scores = {}\n\n    for lst in rank_lists:\n\n        for rank, tid in enumerate(lst):\n\n            scores[tid] = scores.get(tid, 0) + 1 / (k + rank)\n\n    return sorted(scores, key=scores.get, reverse=True)\n\nNode 4 — GROUND (the most important node)\n\nThis is where hallucinated songs die.\n\n• Every candidate must resolve to a real TrackID in the catalog runtime.\n\n• Resolve by (normalized_title, normalized_artist); require artist match for fuzzy title.\n\n• Reject on ambiguity. Never guess.\n\n• Apply hard filters: region license, explicit flag, user dislikes, already-played-in-session, max_per_artist.\n\n• NetEase's three-layer grounding cut entity errors from 17.4% → 9.6% in production.\n\nNode 5 — RERANK\n\nCross-encoder or lightweight LambdaMART over 200 → 30, optimizing:\n\n• completion probability\n\n• save / add-to-playlist probability\n\n• skip-within-30s as the only reliable negative\n\n• diversity penalty (MMR on artist + genre + language)\n\n• scenario rules (bedtime → lower energy; workout → rising energy)\n\nNode 6 — SAY (LLM, streaming)\n\nGenerates playlist title, description, and per-track one-liners only from grounded IDs. If grounding removed half the candidates, the explainer says \"I kept 18 of the 30 I looked at — here's why the rest didn't make the cut.\" Honesty > polish.\n\nA track enters four indexes at ingest time:\n\nIndex Content Model Purpose\n\ntext_vec title + artist + lyrics + tags + editorial BGE-M3 / Qwen3-Embedding \"songs about rain\"\n\naudio_vec mel-spectrogram, 30s clip CLAP / HTS-AT \"sounds like this track\"\n\ncollab_vec item2vec from playlists BPR / Swing \"people who…\"\n\ngraph entities + relations — artist → influencer → genre → era\n\nNew or AI-generated tracks start with zero collaborative signal — which is exactly why the audio+text planes matter. Spotify's shift toward Semantic IDs (quantizing content vectors into discrete tokens an LLM can autoregress) is one clean answer to \"how do you let an LLM speak your catalog\". We borrow the idea: each track gets a 5-token semantic ID, stored alongside its UUID.\n\nIncremental indexing\n\n• New track → audio analysis job (async, ~2s) → write to all indexes in a single transaction with a visible_at timestamp.\n\n• Rights change (label pulls a territory) → tombstone in runtime, not a re-index. Grounding filters it out in <10ms.\n\nConsistency\n\n• Catalog DB is source of truth; vector/graph stores are derived.\n\n• Every night: reconcile counts, repair orphans, rebuild hot-shard HNSW.\n\nPrivacy\n\n• Taste vectors never leave the server unencrypted.\n\n• On-device mini-index (see diagram) handles \"play something from my library\" offline; server handles discovery.\n\nCost control\n\n• 80% of requests never touch the LLM: cached intent templates + retrieval-only path.\n\n• The LLM runs only on UNDERSTAND and SAY. PLAN can be a decision table for the top 50 intents.\n\n• Spotify's team found a ~1B-parameter model is enough for catalog-scale generation when the heavy lifting is done by retrieval and soft-token personalization. We run a 3B quant at the edge and a 7B–14B in the cluster, not 70B+.\n\nOffline ≠ vibes. We track:\n\nLayer Metric\n\nRetrieval Recall@100 per channel, RRF gain vs single-channel\n\nGrounding Hallucination rate (ungrounded IDs surfaced) — target < 0.1%\n\nRanking Completion@30s, skip@30s, save rate, add-to-playlist\n\nSession Playlist dwell time, tracks-per-session, next-day return\n\nGeneration Explanation faithfulness (LLM-as-judge vs human spot-check)\n\nSystem P50 / P99 latency, LLM cost per 1k generations\n\nYouTube Music's discovery work showed the LLM's value came almost entirely from explanation layered on an existing retrieval+rank stack, not from LLM-originated candidates — a result worth remembering before you over-invest in generative retrieval.\n\n• LLM down → serve cached intent patterns; skip SAY; return grounded tracks with template explanations.\n\n• Vector index stale → fall back to collaborative + editorial shelves.\n\n• Grounding rejects >50% → widen title matching, drop artist requirement only for unambiguous titles, and log for review.\n\n• Abusive prompt → refuse at UNDERSTAND; never pass to retrieval.\n\nEvery degradation path still returns real, licensed, playable tracks. A boring playlist beats a broken one.\n\n• No \"one embedding to rule them all.\" Pure vector search lies; pure CF forgets new music.\n\n• No free-form agent loop in the online path. Debugging non-determinism at 2am is not a personality trait.\n\n• No LLM-generated TrackIDs, ever. Not even in tests.\n\n• No training our own foundation model. In 2026, the leverage is in the knowledge layer, not in another 7B music LM.\n\nTL;DR\n\nA music-app knowledge base for LLMs is:\n\n• Three planes (catalog / taste / world), not one vector store\n\n• Multi-modal ingest (audio + text + collaborative + graph)\n\n• A deterministic orchestration graph with a non-negotiable grounding node\n\n• Soft-token personalization instead of per-user fine-tuning\n\n• LLM for intent and explanation; retrieval for truth\n\nThe model is the brain. The knowledge base is the spine. Without the spine, the brain invents songs your users will never be able to play.\n\nIf you've shipped something adjacent — podcasts, short-video BGM, AI music generation, in-car audio — I'd love to compare notes in the comments. Specifically: how do you handle catalog drift when rights change mid-session? That's the one we're still iterating on.", "url": "https://wpnews.pro/news/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms", "canonical_source": "https://dev.to/jackmeng/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms-499d", "published_at": "2026-12-05 08:33:10+00:00", "updated_at": "2026-12-05 08:43:59.830662+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-agents", "ai-products", "mlops"], "entities": ["NetEase", "Spotify", "YouTube Music", "Neo4j", "TigerGraph", "CLAP", "HTS-AT"], "also_reported_by": [], "takeaway": "Split the knowledge layer into a catalog graph, per-user taste vectors and a provenance-tagged RAG corpus, and let the LLM only propose candidates while the runtime verifies existence, licensing and constraints before any track ID reaches the client.", "recommendation": {"advice": "Keep track identity in a verified catalog graph and restrict RAG chunks to explanations, so the model proposes but the runtime confirms existence, licensing and constraints before returning IDs.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms", "markdown": "https://wpnews.pro/news/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms.md", "text": "https://wpnews.pro/news/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms.txt", "jsonld": "https://wpnews.pro/news/designing-a-knowledge-base-architecture-for-a-music-app-powered-by-llms.jsonld"}}