Learning · · 4 min read
Adding Sentiment Analysis to My Python Chatbot with Gemini
I walk through how I added real‑time sentiment detection to my Python chatbot using Gemini, why it matters, and the simple code I use.
When I first heard about using sentiment analysis to make a chatbot feel more human, I wondered how I could add it without spending a lot of money. In this post I show **how to add sentiment analysis to python chatbot** using the free Gemini API, step by step, and share the little tricks that saved me time.
how to add sentiment analysis to python chatbot – the basics
Sentiment analysis simply tells you whether a user’s message sounds happy, sad, angry or neutral. For a chatbot that helps people find information, knowing the tone lets me adjust the reply – a gentle tone for a frustrated user, or a more upbeat one when they’re excited. I first tried a rule‑based approach, but the results were noisy, so I switched to an LLM that can understand context better.
Choosing the right AI model
I evaluated a few options: OpenAI’s sentiment endpoint, Cohere, and Google’s Gemini. Gemini offered a generous free tier and a simple REST interface, which fit my low‑budget setup in Pundri. The model can return a short label and a confidence score, which is perfect for my use case. If you want to see how I set up my development environment, check out my guide on setting up a Python AI development environment.
Setting up the environment
All I need is Python 3.10+, the `requests` library, and the `google-generativeai` SDK. I keep my secrets in Supabase Edge Functions so they never touch my local machine. Here’s the minimal install command:
pip install google-generativeai requests
Next, I store the Gemini API key in Supabase's secret manager and load it at runtime. The same approach works for other keys, so you can reuse this pattern for future projects like adding vector search to my Python chatbot.
Fetching user messages and sending to Gemini
My chatbot already receives a plain text message from the front‑end. I wrap that text in a small prompt that asks Gemini to classify the sentiment. The prompt is deliberately short – the model works better with clear instructions.
def get_sentiment(message: str) -> dict:
prompt = f"Classify the sentiment of the following user message and give a confidence score between 0 and 1. Respond with a JSON object containing 'sentiment' (one of 'positive', 'negative', 'neutral') and 'score'.\n\nMessage: \"{message}\""
response = genai.generate_content(prompt)
# Gemini returns a string, so we parse it safely
try:
result = json.loads(response.text)
except Exception:
# fallback in case of formatting issues
result = {'sentiment': 'neutral', 'score': 0.5}
return result
The function returns a dictionary like `{'sentiment': 'negative', 'score': 0.82}`. I keep the score because I sometimes want to be more conservative – for example, I only change the tone if the confidence is above 0.7.
Interpreting Gemini's response
Gemini’s output is easy to read, but a few things can go wrong: extra whitespace, missing fields, or a different language. I added a tiny validation step that maps any unknown sentiment to 'neutral' and clamps the score between 0 and 1. This keeps the chatbot from crashing on edge cases.
- positive – user is happy or optimistic
- negative – user sounds upset or frustrated
- neutral – no strong emotion detected
Using sentiment to improve the conversation
Now that I have the sentiment, I feed it into the response generator. If the sentiment is negative and the confidence is high, I prepend a calming sentence: "I’m sorry you’re having trouble, let me help you step by step." For positive sentiment, I add an enthusiastic line like "Great! Let’s keep the momentum going." The rest of the reply comes from the same Gemini prompt that powers the chatbot, so the overall style stays consistent.
Here’s a tiny snippet that shows how I combine the two parts:
def build_reply(user_message: str) -> str:
sentiment_info = get_sentiment(user_message)
base_reply = generate_chatbot_reply(user_message) # your existing function
if sentiment_info['sentiment'] == 'negative' and sentiment_info['score'] > 0.7:
prefix = "I understand this can be frustrating. "
elif sentiment_info['sentiment'] == 'positive' and sentiment_info['score'] > 0.7:
prefix = "Awesome! "
else:
prefix = ""
return prefix + base_reply
The change feels small, but when I tested it with a few friends, they told me the bot sounded more attentive. It also gave me a concrete metric to improve – if the negative‑sentiment detection is often wrong, I can tweak the prompt or try a different Gemini model.
If you’re curious about other ways to make a chatbot smarter, I also wrote about adding real‑time chat streaming and how I use AI without outsourcing my thinking. Feel free to explore my projects to see the full code base.
Takeaway
Adding sentiment analysis doesn’t require a heavyweight ML pipeline; a few lines of prompt engineering and a free LLM can give you useful signals. Start with a clear prompt, handle the response safely, and use the sentiment to adjust tone. The next step for me is to combine sentiment with user intent, so the bot can both understand what the user wants and how they feel.
Frequently asked questions
How can I get a free Gemini API key?
Sign up at Google AI Studio, create a new Gemini project and enable the API. The free tier gives you a limited number of requests each month, which is enough for small chatbots and learning experiments.
What should I do if Gemini returns malformed JSON?
Wrap the call in a try‑except block, fall back to a default neutral sentiment, and optionally log the raw response for debugging. Adding a small validation step, as shown in the post, prevents crashes.
Can I use this sentiment approach with other LLM providers?
Yes. The same prompt works with most LLMs that support JSON output. Just replace the Gemini SDK call with the provider’s request method and adjust any parameter names accordingly.