pip install huggingchat
pip install gradio # For building web interface
pip install torch transformers # Basic dependencies
from huggingchat import ChatBot # Create chatbot instance
bot = ChatBot() # Send a message and get a response
response = bot.chat("Hello, please introduce yourself!")
print(response)
import gradio as gr
from huggingchat import ChatBot
def chat_response(message, history):
bot = ChatBot()
response = bot.chat(message)
return response # Create web interface
demo = gr.ChatInterface(
chat_response,
title="My AI Assistant",
description="Welcome to chat with me!",
theme="soft") # Launch service
demo.launch()
from huggingchat import ChatBot
from transformers import AutoTokenizer, AutoModelForCausalLM # Load custom model
model_name = "your-preferred-model"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name) # Create chatbot with custom model
bot = ChatBot(model=model, tokenizer=tokenizer)
class ChatBotWithMemory:
def __init__(self):
self.bot = ChatBot()
self.history = []
def chat(self, message):
# Use conversation history as context
context = "\n".join(self.history[-5:]) # Keep the last 5 rounds of conversation
full_message = f"{context}\n{message}" if context else message
response = self.bot.chat(full_message)
# Update history
self.history.append(f"User: {message}")
self.history.append(f"Bot: {response}")
return response # Use chatbot with memory
memory_bot = ChatBotWithMemory()
print(memory_bot.chat("Hello"))
print(memory_bot.chat("What did we talk about earlier?"))
from transformers import pipeline
class EmotionalChatBot:
def __init__(self):
self.bot = ChatBot()
self.sentiment_analyzer = pipeline("sentiment-analysis")
def chat(self, message):
# Analyze the sentiment of the user's message
sentiment = self.sentiment_analyzer(message)[0]
# Adjust the response style based on sentiment
if sentiment['label'] == 'POSITIVE':
prompt = f"Respond in a positive tone: {message}"
else:
prompt = f"Respond in a comforting tone: {message}"
return self.bot.chat(prompt) # Create chatbot with sentiment analysis
emotional_bot = EmotionalChatBot()
import gradio as gr
from huggingchat import ChatBot
def create_app():
bot = ChatBot()
def chat(message, history):
response = bot.chat(message)
return response
app = gr.ChatInterface(
chat,
title="AI Assistant",
description="Available 24/7 to serve you",
theme="soft" )
return app # Create app
app = create_app() # Launch service (can be deployed to cloud)
app.launch(server_name="0.0.0.0", server_port=7860)
-
Please ensure your Python version is ≥3.7 -
The first run will download the model, which may take some time -
Using a GPU can significantly improve response speed -
Remember to save conversation history in a timely manner to avoid data loss