Music AI
Table of contents
Building a Mood-Based Playlist Generator with AI: How I Connected Emotions to Music
A step-by-step journey of combining FastAPI, OpenAI, and Spotify to create personalized music experiences
We've all been there: trying to find the perfect playlist that matches exactly how we're feeling. Maybe you're "feeling nostalgic about rainy summer days" or need "upbeat focus music to power through a deadline." Traditional playlist searches just don't capture these nuanced emotional states.
That's why I built a Mood-Based Playlist Generator—an API that combines the intelligence of OpenAI's language models with Spotify's vast music library to create personalized playlists based on mood descriptions. In this article, I'll walk you through how I built it, the challenges I faced, and how you can create your own.
The Vision: Translating Emotions to Music
The idea was simple but powerful: what if you could describe exactly how you're feeling, and AI would curate the perfect soundtrack? No more endless scrolling through generic playlists or spending hours creating your own.
My application bridges three key components:
- Your emotional state: Described in natural language
- AI understanding: Translating those emotions into musical attributes
- Music discovery: Finding and compiling songs that match those attributes
The Building Blocks
Technologies Used:
- FastAPI: For creating a lightweight, high-performance API
- OpenAI API: For understanding mood descriptions and generating song suggestions
- Spotify Web API: For searching songs and creating playlists
- Python: Bringing it all together
System Architecture
The application flow works like this:
- User authenticates with Spotify
- User describes their mood ("anxious but ready to conquer the day")
- OpenAI generates appropriate song search queries
- The app searches Spotify for matching songs
- A custom playlist is created in the user's Spotify account
- The user receives a link to their new mood-matched playlist
Building the API: A Closer Look
Let's break down the key components of the code:
Authentication Flow
The first challenge was implementing Spotify's OAuth flow, which requires several steps:
def get_spotify_auth_url(): scope = "playlist-modify-private playlist-modify-public user-read-private" auth_url = f"https://accounts.spotify.com/authorize?client_id={SPOTIFY_CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={scope}" return auth_url def access_token(auth_code): auth_header = base64.b64encode(f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}".encode()).decode() # Request token from Spotify...
This gives our application permission to create playlists in the user's Spotify account.
The Magic: AI-Powered Song Selection
The heart of the application is the mood interpretation. I use OpenAI's models to translate a mood description into concrete song suggestions:
def generate_song_queries(mood_description, num_songs=10): prompt = f""" Generate {num_songs} specific song search queries based on the following mood description: "{mood_description}" Each query should be a SIMPLE search term without special formatting. For example: "Adele Hello" or "Ed Sheeran Shape of You" """ response = openai.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a music expert that suggests songs matching specific moods."}, {"role": "user", "content": prompt} ], response_format={"type": "json_object"} )
This approach leverages OpenAI's understanding of both language and music culture to generate relevant song suggestions. The model remarkably understands the emotional tones that certain artists and songs evoke.
Bringing It All Together
With song suggestions in hand, the API then:
- Searches for these songs on Spotify
- Creates a new playlist in the user's account
- Adds the found songs to the playlist
- Returns the playlist details to the user
Challenges and Lessons Learned
Authentication Headaches
One of the most frustrating bugs was with the Spotify authentication. The error message "Only valid bearer authentication supported" kept appearing.
The fix was surprisingly simple but easy to miss: the token formatting had extra spaces. This taught me the importance of clean auth token handling:
# Properly format the access token by removing any extra spaces or quotes if access_token: access_token = access_token.strip() if access_token.startswith('"') and access_token.endswith('"'): access_token = access_token[1:-1]
OpenAI Prompt Engineering
Getting the right song suggestions required careful prompt design. Initially, I was getting songs that were too obscure or didn't match the mood well. The solution was to be more specific in the prompt:
Generate {num_songs} specific song search queries based on the following mood description:
"{mood_description}"
Each query should be a SIMPLE search term without special formatting.
This illustrates how critical prompt engineering is when working with AI models.
The Results: Emotional Intelligence in Playlists
The resulting playlists have been surprisingly spot-on. For example:
-
Mood: "Nostalgic about the early 2000s but feeling optimistic"
-
Result: A mix of 2000s hits with upbeat, forward-looking tracks
-
Mood: "Need focus but feeling creative and slightly rebellious"
-
Result: A blend of instrumental focus music with creative, boundary-pushing tracks
How You Can Build This Too
Want to create your own mood-based playlist generator? Here's how to get started:
-
Set up your environment:
pip install fastapi uvicorn python-dotenv requests openai
-
Create developer accounts:
- Sign up for Spotify Developer
- Get an API key from OpenAI
-
Clone the repository and set up your environment variables:
SPOTIFY_CLIENT_ID=your_spotify_client_id SPOTIFY_CLIENT_SECRET=your_spotify_client_secret OPENAI_API_KEY=your_openai_api_key REDIRECT_URI=http://localhost:8888/callback
The repo: https://github.com/Chukwuebuka-2003/mood-playlist-ai
- Run the application:
python api.py
The Future of Emotional AI and Music
This project is just the beginning of what's possible at the intersection of AI and music. Future enhancements could include:
- Analyzing audio features: Using Spotify's audio features API to match songs based on danceability, energy, tempo, etc.
- Learning from feedback: Incorporating user feedback to improve recommendations
- Multi-modal input: Accepting images or voice to detect emotional states
Conclusion: The Personal Touch in the Streaming Era
In an age of algorithmic recommendations, there's something powerful about describing your exact emotional state and getting music that resonates. This project shows how AI can help create deeply personalized experiences that connect with us on an emotional level.
Music has always been about emotion, and now technology is helping us bridge the gap between what we feel and what we hear. The code for this project is available on GitHub, and I welcome contributions and ideas for how to make this emotional-musical connection even stronger.
Have you ever wanted a playlist that perfectly matches your mood? What moods would you want to translate into music? Share your thoughts in the comments!
Models
There are no models linked
Datasets
There are no datasets linked