
Week 6 Instructions for Spotify Agent
Hi All, welcome to week 6 of the Spotify Agent project.
This week, we'll be creating a web frontend for our Spotify agent using Streamlit, which will provide a user-friendly chat interface that connects to our FastAPI backend.
While our FastAPI backend works great for API calls, regular users need a visual interface to interact with our agent.
Streamlit is a Python framework that makes it easy to create web applications for data science and AI projects. It's perfect for our use case because:
- Simple: Write web apps using pure Python
- Fast: Quick to develop and iterate
- Interactive: Built-in chat components and widgets
- No HTML/CSS needed: Focus on functionality, not web design
First, install Streamlit in your environment:
uv pip install streamlit
## Creating Our Frontend
Create a new file called app.py in your spotify-agent folder. We'll build this step by step.
*import os
from dotenv import load_dotenv
import streamlit as st
from langchain_core.messages import AIMessage, HumanMessage
from agent_script import invoke_our_graph, create_graph
import asyncio
import nest_asyncio
import time
import requests
load_dotenv() # Load environment variables from a .env file if present*
These imports give us:
- Streamlit: For the web interface
- LangChain messages: For proper message formatting
- Requests: To call our FastAPI backend
- Time: For streaming text effects
st.title("🎵Spotify Agent🎵")
This creates the main title for our web app
Streamlit uses session state to remember data across user interactions:
Session state essentially preserves objects as long as our user interacts with the interface
copy the following into your code
*if "messages" not in st.session_state:
# default initial message to render in message state
st.session_state["messages"] = [AIMessage(content="How can I help you?")]
if "agent" not in st.session_state:
st.session_state["agent"] = asyncio.run(create_graph())
agent = st.session_state["agent"]*
What this does:
- messages: Stores the chat conversation history
- agent: Stores the agent instance (created once per session)
- Initial message: Shows a welcome message when the app starts
Read the following documentation page to understand how langgraph interacts with Streamlit
https://docs.streamlit.io/develop/api-reference/chat/st.chat_message
Now copy the following into your app.py file
*
for msg in st.session_state.messages:
if type(msg) == AIMessage:
st.chat_message("assistant").write(msg.content)
if type(msg) == HumanMessage:
st.chat_message("user").write(msg.content)*
This code:
- Loops through all messages in the session
- Renders AI messages with an "assistant" avatar
- Renders user messages with a "user" avatar
- Maintains chat history throughout the session
### Step 5: Handle User Input and API Calls
*# takes new input in chat box from user and invokes the graph
if prompt := st.chat_input():
st.session_state.messages.append(HumanMessage(content=prompt))
st.chat_message("user").write(prompt)
# Process the AI's response and handles graph events using the callback mechanism
with st.chat_message("assistant"):
serialized_messages = [msg.dict() if hasattr(msg, 'dict') else msg for msg in st.session_state.messages]
output = requests.post("http://localhost:8000/chat", json={"input": serialized_messages})
output = output.json()
text = output["response"]["messages"][-1]['content']
print(text)
placeholder = st.empty()
streamed_text = ""
for token in text.split():
streamed_text += token + " "
placeholder.write(streamed_text)
time.sleep(0.07) # Adjust speed as needed
st.session_state.messages.append(AIMessage(content=text))*
This section:
- Captures user input from the chat box
- Adds user message to session state and displays it
- Serializes messages for the API call
- Calls our FastAPI backend at http://localhost:8000/chat
- Streams the response word by word so it looks nicer
- Saves the AI response to session state
### Step 1: Start Your Backend
First, make sure your FastAPI backend is running:
uvicorn backend:app --reload --host 0.0.0.0 --port 8000
In a new terminal, run:
streamlit run app.py
You should be able to click on a link in terminal that will take you to your frontend
Congratulations! You now have a web application for your Spotify agent!