Login Sign Up

Building an Interactive Movie Recommender with Semantic Kernel and TMDB API

Chatbots have become an essential part of modern applications, providing seamless user interaction. By integrating an external API, such as The Movie Database (TMDB), into a chatbot, we can enhance its capabilities by providing real-time movie recommendations, genres, and trending films.

In this tutorial, we will walk through the process of integrating the TMDB API into a chatbot using Semantic Kernel (SK) and Python.

Part 1: Setting Up the TMDB API and Semantic Kernel

Step 1: Getting the TMDB API Key

To access movie data, register at TMDB and generate an API key:

  1. Sign up for a free account.
  2. Go to Settings > API > Request an API Key.
  3. Save the generated API key; we’ll need it in the next steps.

Step 2: Installing Dependencies

Make sure you have the required Python libraries installed:

pip install semantic-kernel requests asyncio

Step 3: Creating the TMDB Service Module

Now, let’s create a Python file tmdb_service.py, which will act as the semantic layer for our chatbot:

from semantic_kernel.functions import kernel_function

import requests

class TMDbService:

    def __init__(self, api_key: str):

        self.api_key = api_key

    @kernel_function(

        description="Gets the movie genre ID for a given genre name",

        name="get_movie_genre_id",

        input_description="The movie genre name to get the genre_id"

    )

    def get_movie_genre_id(self, genre_name: str) -> str:

        url = f"https://api.themoviedb.org/3/genre/movie/list?api_key={self.api_key}&language=en-US"

        response = requests.get(url)

        if response.status_code == 200:

            genres = response.json()['genres']

            for genre in genres:

                if genre_name.lower() in genre['name'].lower():

                    return str(genre['id'])

        return None

The above code initializes a TMDbService class and provides a function to retrieve genre IDs from TMDB.

Part 2: Creating a Chatbot to Fetch Movie Data

Step 4: Fetching Top Movies by Genre

Let’s extend tmdb_service.py to fetch currently playing movies by genre:

@kernel_function(

    description="Gets a list of currently playing movies for a given genre",

    name="get_top_movies_by_genre",

    input_description="The genre of the movies to get"

)

def get_top_movies_by_genre(self, genre: str) -> str:

    genre_id = self.get_movie_genre_id(genre)

    if genre_id:

        url = f"https://api.themoviedb.org/3/movie/now_playing?api_key={self.api_key}&language=en-US"

        response = requests.get(url)

        if response.status_code == 200:

            movies = response.json()['results']

            filtered_movies = [movie['title'] for movie in movies if str(genre_id) in map(str, movie['genre_ids'])][:10]

            return ", ".join(filtered_movies)

    return "No movies found for this genre."

This function retrieves a list of top movies in a specific genre using TMDB’s now playing API.

Step 5: Testing the TMDB API Functions

Before integrating into a chatbot, let’s test our functions using a simple script test_tmdb_service.py:

import asyncio

from tmdb_service import TMDbService

async def main():

    api_key = "your-tmdb-api-key"

    tmdb_service = TMDbService(api_key)

    print("Genre ID for Action:", tmdb_service.get_movie_genre_id("Action"))

    print("Top Action Movies:", tmdb_service.get_top_movies_by_genre("Action"))

if __name__ == "__main__":

    asyncio.run(main())

Run this script to verify that the API functions work correctly:

python test_tmdb_service.py

Part 3: Building the Interactive Chatbot

Step 6: Creating the Chatbot Interface

Now, let’s create chatbot.py, which will integrate TMDB API functions into a chatbot:

import asyncio

import semantic_kernel as sk

from tmdb_service import TMDbService

async def chat():

    api_key = "your-tmdb-api-key"

    kernel = sk.Kernel()

    tmdb_service = kernel.import_plugin_from_object(TMDbService(api_key), "TMDBService")

    print("Welcome to the Movie Chatbot! Type 'exit' to quit.")

    while True:

        user_input = input("User:> ")

        if user_input.lower() == "exit":

            print("Exiting chat...")

            break

        response = await tmdb_service["get_top_movies_by_genre"](kernel, sk.KernelArguments(genre=user_input))

        print(f"Chatbot:> {response}")

if __name__ == "__main__":

    asyncio.run(chat())

Step 7: Running the Chatbot

Run the chatbot using:

> python chatbot.py

In this tutorial, we successfully:

  • Set up TMDB API access
  • Created a semantic layer using Semantic Kernel
  • Built functions to fetch movie genres and top movies
  • Integrated the API into an interactive chatbot

This chatbot can be expanded further by adding:

  • Search functionality for specific movies
  • Trending movies and TV shows
  • Personalized recommendations based on user preferences