đŻÂ Learning Goals
- Explain what Hugging Face is and the role it plays in the machine learning community
- Build a Hugging Face Space that hosts a Gradio application
- Understand the structure and input requirements of functions used by Gradio components
đ Technical Vocabulary
- Hugging Face
- Gradio
- ChatInterface
- Version control
Â
Warm-Up
Compare these two blocks of code. Whatâs the same and whatâs different?
def calculate_mean(numbers): total = 0 for num in numbers: total += num return total / len(numbers) nums = [10, 20, 30, 40, 50] print(calculate_mean(nums))
import numpy as np nums = [10, 20, 30, 40, 50] print(np.mean(nums))
This example highlights how pre-built libraries can simplify your code and reduce the chance for errors, allowing you to focus on building more complex features. Today, weâll be interacting with a new library called Gradio! Just like the
numpy library simplifies common mathematical calculations, gradio is a Python library that simplifies building interactive user interfaces. With just a few lines of code, youâll be able to create an interactive chatbot thatâs ready for user input!What is Gradio?
Gradio is a user-friendly Python library that lets you quickly create interactive web apps for your projects, so that you can spend more time refining the other parts of your app! Imagine being able to build a cool, clickable interface where anyone can try out your AI model without needing to see all the complicated code behind it. It's like designing a simple control panel for your project and making it easy for others to use and explore.
What is Hugging Face?
Weâll be building our Gradio apps on a platform called Hugging Face. Hugging Face is a tech company and community that makes it easier for everyoneâfrom beginners to expertsâto work with artificial intelligence. Think of it as a huge online toolbox where you can find ready-made models to help with tasks like building chatbots, translating languages, or even generating creative writing. Itâs also a place where people share their projects and learn from each other, making the world of AI fun and accessible.
Hugging Face Spaces
Youâll build your chatbot today in a Hugging Face Space. A Space on Hugging Face allows you to quickly build your app in the browser and share it with others! With Spaces, you donât have to worry about complicated setups or backend servers; you simply upload your project and let others explore and interact with it.
Version Control
When you're making changes in the browser on a Hugging Face Space, version control works behind the scenes using Gitâthe same system that many professional developers use. Think of version control as a âsave gameâ feature for your project. Every time you make changes and save them, a snapshot or âcommitâ of your work is created. This snapshot includes a brief message describing the change you made, like âfixed the chatbot responseâ or âchanged autofocus.â In short, whenever you âcommitâ your project, thatâs really just another way of saying that youâre saving this version of your project!
These commits build a timeline of your projectâs history, allowing you to see how your code has evolved over time. If something goes wrong, you can always revert back to an earlier version. Even though you're working entirely within the browser, this system makes it easy to experiment, keep track of your progress and collaborate with others.
Getting Started
- Create a Hugging Face Account:
- Visit the Hugging Face website and click on âSign Up.â
- Complete the registration process and verify your email address.
- Take a Tour of Hugging Face:
- Once logged in, check out the âModelsâ, âDatasetsâ, and âSpacesâ sections.
- What kinds of models are available on Hugging Face?
- Click on a few Spaces to see whatâs possible!
- Set Up Your First Space:
- Navigate to the âSpacesâ section.
- Click on â+ New Space.â
- Choose a name for your Space. You can skip the description and license for now.
- Choose Gradio for the SDK and select Blank for the template.
- Weâll be writing the code ourselves, so we wonât use the âchatbotâ template! đ
- Keep the CPU Basic selection.
- Select public visibility and âCreate Spaceâ!
Click here to see a screenshot of this step!
- Create the
app.pyfile! - To get started with your Hugging Face space, you need an
app.pyfile. - This file contains the primary code that defines and launches your application. When your Space starts, the code in
app.pyis executed automatically. - Scroll down and click on the link in the option that says, âAlternatively, you can create the
app.pyfile directly in your browser.â This will create your Python file and open a text editor where you can write your code, very similar to the code cells in Google Colab.
Click here to see a screenshot of this step!
- Youâre ready to start coding! đ
When your screen looks like the image below, youâre ready to begin.
Getting Started: Code-Along
Weâll build this first chatbot together. Complete each step in your own Hugging Face space.
- Import Gradio with
import gradio as gr.
- Now weâll use the
ChatInterface()from Gradio to quickly build a chatbot UI with two sections: the conversation history and an input for the user to type their questions. Weâll assign thatChatInterface()to a variable called chatbot:chatbot = gr.ChatInterface().
- Finally, we need to launch the chatbot by calling the
launch()function on thechatbotobject:chatbot.launch().
- If you run this file right now, youâll see an error message! The
ChatInterfacefunction requires one argument, a function that controls the response of the chatbot based on the user input and chat history. For now, weâll make our chatbot simply respond with the exact same message the user enters. Above thechatbot = gr.ChatInterface()line, letâs define a function calledechoand then pass it to theChatInterface()function. At this point, your entireapp.pyfile should match this: - When you build a normal function, you're usually the one who calls it and decides what values to pass in. In this case, you never call
echoyourself! Instead, you hand it off togr.ChatInterface(), and Gradio calls it automatically each time the user submits a message. - The
echofunction has two parameters that Gradio is responsible for passing in every time the user sends a message. When Gradio calls theechofunction, it always passes in two values: the user's most recent input (a string of text) as the first argument, and a list of all the previous back-and-forth messages in the conversation as the second. We've named thesemessageandhistoryhere, but those names are entirely up to you! You could just as easily writedef echo(user_input, chat_log):and it would work exactly the same way. - What Gradio actually cares about is position, not name. That means the order does matter: Gradio will always pass the current user input first and the conversation history second, regardless of what you call them. If you accidentally flip the order and write
def echo(history, message):, your function will treat the conversation history as the current input and vice versa, causing your chatbot to behave in unexpected ways. For now, our simple echo bot ignores the history entirely and just returns whatever the user typed, but once you start building more sophisticated chatbots, you'll use that second parameter to craft responses that reference earlier parts of the conversation!
import gradio as gr def echo(message, history): return message chatbot = gr.ChatInterface(echo) chatbot.launch()
Letâs clarify a few things we wrote here:
- To save the changes, click the âCommit new file to mainâ button.
Pro-Tip: Itâs best to change the commit message to something specific about what you changed, so that if you wanted to go back to this version, youâd know what changed at that moment in time!
- It may take a few minutes for your app to load, especially the first time. Be patient! The little pill at the top that shows the app status will turn green and display a âRunningâ message when itâs ready. Click the âAppâ option in the menu under the name of your app to see your app in action! Try sending a message to see how it works.
Click here to see a screenshot of this step!
YOU DID IT! đ
Take a moment to celebrate! You just built your first chatbot!!! Well done. Now letâs continue building to see what else we can do.
The icons at the top of the App view give you access to different tools related to your project.
- Click the
Filesbutton. Here, you can see that you have not just one, but three files in your project! - The
app.pyfile that we already edited! Itâs the main file that defines and launches the application. - The
.gitattributesis a configuration file used by Git to define how it should handle tracking changes to your files. You never need to edit this one! - The
README.mdfile is a markdown file that serves as the primary documentation for your project. Youâre welcome to make changes to this file, but it wonât be visible in the main App view. Itâs usually used to share information about your project with other developers and itâs only visible to people who navigate to your project files.
- If you click on the
Logsicon, you can see error messages or warnings that might pop up when you launch your app. This is also where any logs fromprint()statements will appear!
Try-It | Modify the Chatbot Function
Right now our chatbot simply repeats whatever the user types, but that's not very interesting! Let's make it a little more dynamic. Instead of echoing the user's message back, our chatbot will respond with either âYesâ or âNoâ, chosen at random. To do this, we'll import Python's built-in
random library and make a small change to our function.- At the top of your file, add
import randomon a new line belowimport gradio as gr. This gives you access to Python's built-inrandomlibrary, which youâll use to randomly pick between two responses.
- Modify the
echofunction. Rename the function to more accurately reflect the functionâs new job. Letâs rename itrespondinstead, because itâs new job is to respond with âYesâ or âNoâ.
- Change the function body so that instead of returning the message that the user typed, the function returns
random.choice(["Yes", "No"]). random.choice()takes a list of options and randomly picks one. Here we're passing it a list with two strings:"Yes"and"No". Every time the user sends a message, Python will randomly select one of those two options to return.- Notice that the
echofunction still takesmessageandhistoryas parameters, even though we're not using either of them anymore. That's okay! Gradio still needs the function to accept those two arguments. We don't have to use them.
- Commit your changes, wait for your Space to rebuild, and then try sending a few messages to your chatbot. It should respond with either âYesâ or âNoâ each time!
Discuss
What does the Gradio ChatInterface() expect as a parameter?
The
ChatInterface() requires at least one parameter: a function. This function is passed two arguments: message and history where message represents the userâs message and history is the entire conversation. These are positional arguments, so they can be called anything you want, but the first argument will always represent the userâs input (a string) and the second argument will be the conversation history (a list of dictionaries).What happens if you don't include one of these inputs for the function?
Youâll get an error message like this one: âTypeError:
respond() takes 1 positional argument but 2 were givenâ. Both of these inputs are required for the ChatInterface() to function as expected.ChatInterface Options
The
ChatInterface() requires only one parameter, the function that controls the response, but there are additional parameters that can modify the chatbotâs behavior and appearance. Remember how we set the type to âmessagesâ by passing in an additional type parameter? Check out the Gradio ChatInterface docs to see a complete list of the parameters available.Try-It | Add More Parameters
Add a title and a description to your chatbot by passing additional parameters to the
ChatInterface(). Reference the docs for the exact syntax!đśď¸Â Mild Challenge: Test out another optional parameter to see how it changes your chatbot.
Practice
Practice | Hugging Face & Gradio
Create a Magic 8 Ball chatbot! If youâve never seen a Magic 8 Ball before, essentially the user asks a yes or no question to the ball and then turns it over to reveal a random answer that displays in a window. The original version had up to 20 different possible responses, including âWithout a doubtâ and âOutlook not so goodâ. Feel free to get creative with the responses for your Magic 8 Ball chatbot! At a minimum, your chatbot should have at least 3 different responses.
đ¤Â AI Connection
Need inspiration for your Magic 8 Ball responses? Ask an AI tool: "Give me 10 creative Magic 8 Ball responses that are funny and teen-friendly. It should be a mix of positive, negative, and vague answers." Pick your favorites, remix them to match your style, and add any of your own. That way you can spend more time on the code and less time staring at a blank list!
đź Takeaways
Congratulations on building your first chatbot in Hugging Face! Your final project will also be a chatbot hosted on a Hugging Face Space, but instead of always responding the exact same way or responding based on a limited number of options, your chatbots will use text generation models to dynamically respond to user input. Weâll explore how to do that in the coming days, but for now, letâs review the key takeaways from this lesson:
- Hugging Face is a community and platform where you can deploy and share your interactive projects using Spaces
- Gradio is a user-friendly Python library for building interactive web apps quickly
- Gradioâs
ChatInterfacerequires a function with two inputs:messageandhistory
For a summary of this lesson, check out the 10. Chatbot Lab One-Pager!
Â