Share
Explore

icon picker
Creating a Simple AI App using Hugging Face Spaces

Lab Workbook: Creating a Simple AI Chatbot with Hugging Face Spaces

megaphone
Introduction to Hugging Face Spaces
Lab instruction set with updates to ensure compatibility with the current GitHub authentication mechanisms.

Creating a Simple AI Chatbot with Hugging Face Spaces

## Introduction to Hugging Face Spaces
Hugging Face Spaces is a platform that allows developers to easily host and share machine learning models and applications. It provides a simple way to deploy AI models and create interactive demos without needing to set up the infrastructure. This is the concept of Serverless PaaS (Platform As A Service).
In this lab, we'll create a simple chatbot using a pre-trained language model and deploy it on Hugging Face Spaces.

Setting Up

Step 1: Create a Hugging Face Account
1. Go to [Hugging Face](https://huggingface.co/). 2. Click "Sign Up" and follow the prompts to create an account.

Step 2: Set Up a GitHub Account (if you don't have one)
1. Go to [GitHub](https://github.com/). 2. Click "Sign up" and follow the prompts to create an account.

Step 3: Install Git on Your Local Machine
1. Download and install Git from [Git-SCM](https://git-scm.com/downloads).
Step 4: Configure Git with Your GitHub Credentials
```bash git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
Creating the Chatbot Application
Step 1: Create a New GitHub Repository
1. Go to [GitHub New Repository](https://github.com/new). 2. Name your repository "simple-chatbot". 3. Choose "Public" and initialize with a README. 4. Click "Create repository".

Step 2: Clone the Repository to Your Local Machine
```bash git clone https://github.com/your-username/simple-chatbot.git cd simple-chatbot ```
Step 3: Create the Necessary Files for Your Chatbot
**app.py:**
```python import gradio as gr from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "microsoft/DialoGPT-small" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name)
def chatbot(input_text): input_ids = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors="pt") chat_history_ids = model.generate( input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, ) response = tokenizer.decode(chat_history_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True) return response
iface = gr.Interface(fn=chatbot, inputs="text", outputs="text") iface.launch() ```
**requirements.txt:**
``` transformers torch gradio ```
Using Personal Access Tokens (PATs):
1. Generate a PAT from your GitHub settings. 2. Use the PAT when prompted for a password during the `git push` operation.
```bash git add . git commit -m "Initial commit: Simple chatbot application" git push origin main ```
Using GitHub CLI:
1. Authenticate with GitHub CLI:
```bash gh auth login # Follow the prompts to authenticate ```
2. Commit and push your changes:
```bash git add . git commit -m "Initial commit: Simple chatbot application" git push origin main ```

Deploying to Hugging Face Spaces

Step 1: Create a New Space
1. Go to [Hugging Face Spaces](https://huggingface.co/spaces). 2. Click "Create new Space". 3. Choose a name for your Space (e.g., "simple-chatbot"). ​4. Select "Gradio" as the SDK. 5. Choose "Public" visibility. 6. Click "Create Space".
### Step 2: Link Your GitHub Repository
1. In your new Space, go to the "Files" tab. 2. Click on "Add file" and select "Repository". 3. Choose your GitHub account and select the "simple-chatbot" repository. 4. Click "Link repository".
Your application will now be automatically deployed to Hugging Face Spaces. You can view it by clicking on the "App" tab in your Space.
## Testing Your Chatbot
### Step 1: Interact with Your Chatbot
1. Go to the "App" tab in your Hugging Face Space. 2. Type a message in the input box and press Enter. 3. Observe the chatbot's response.
### Step 2: Share Your Chatbot
1. Copy the URL of your Space (e.g., `https://huggingface.co/spaces/your-username/simple-chatbot`). 2. Share this URL with others so they can interact with your chatbot.
## Creating a Python Client
### Create a New File Called `client.py` in Your Local Repository
**client.py:**
```python import requests
def chat_with_bot(message): url = "https://your-username-simple-chatbot.hf.space/api/predict" data = {"data": [message]} response = requests.post(url, json=data) return response.json()["data"][0]
# Test the client while True: user_input = input("You: ") if user_input.lower() == 'quit': break response = chat_with_bot(user_input) print(f"Bot: {response}") ```
Replace `your-username` in the URL with your actual Hugging Face username.
### To Use This Client:
1. Install the `requests` library:
```bash pip install requests ```
2. Run the script:
```bash python client.py ```
3. Type messages and see the bot's responses. 4. Type 'quit' to exit the program.
### Remember to Add `client.py` to Your GitHub Repository
```bash git add client.py git commit -m "Add Python client for chatbot API" git push origin main ```

Homework/Extension Activities

- Modify the chatbot to use a different pre-trained model (e.g., "microsoft/DialoGPT-medium" or "microsoft/DialoGPT-large").
- Add a feature to maintain conversation history.
- Implement error handling in both the Space app and the Python client.
- Create a web interface for your chatbot using Flask or Django.
- Explore other Hugging Face models and create a different type of application (e.g., text classification, named entity recognition).

Citations: [1] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/6136/af1d70c3-9a61-4fd5-8ad0-243225ce7acf/Creating%20a%20Simple%20AI%20App%20using%20Hugging%20Face%20Spaces%20.pdf [2] https://docs.github.com/en/authentication [3] https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens [4] https://cli.github.com/manual/gh_auth_login [5] https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/changing-your-two-factor-authentication-method [6] https://stackoverflow.com/questions/18935539/authenticate-with-github-using-a-token [7] https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-authentication-to-github


#############################################################################
This lab workbook provides a comprehensive guide to creating a simple AI chatbot using Hugging Face Spaces, from setup to deployment and testing. Students can follow these steps independently to create their own functional AI application.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.