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.
To access movie data, register at TMDB and generate an API key:
Make sure you have the required Python libraries installed:
pip install semantic-kernel requests asyncioNow, 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 NoneThe above code initializes a TMDbService class and provides a function to retrieve genre IDs from TMDB.
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.
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.pyNow, 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())Run the chatbot using:
> python chatbot.pyIn this tutorial, we successfully:
This chatbot can be expanded further by adding: