The below is the code on google colab that test the llama model for chat:"!pip install…
- User
The below is the code on google colab that test the llama model for chat:"!pip install transformers torch accelerate !pip install --upgrade gradio
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
!huggingface-cli login from transformers import AutoTokenizer import transformers import torch
model = "meta-llama/Llama-2-7b-chat-hf" # meta-llama/Llama-2-7b-chat-hf
tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True) from transformers import pipeline
llama_pipeline = pipeline( "text-generation", # LLM task model=model, torch_dtype=torch.float16, device_map="auto", ) def get_response(prompt: str) -> None: """ Generate a response from the Llama model.
Parameters: prompt (str): The user's input/question for the model. Returns: None: Prints the model's response. """ sequences = llama_pipeline( prompt, do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=256, ) print("Chatbot:", sequences[0]['generated_text'])get_response("Hi, I'm Kris") SYSTEM_PROMPT = """[INST] <> You are a helpful bot. Your answers are clear and concise. <>
"""
Formatting function for message and history
def format_message(message: str, history: list, memory_limit: int = 3) -> str: """ Formats the message and history for the Llama model.
Parameters: message (str): Current message to send. history (list): Past conversation history. memory_limit (int): Limit on how many past interactions to consider. Returns: str: Formatted message string """ # always keep len(history) <= memory_limit if len(history) > memory_limit: history = history[-memory_limit:] if len(history) == 0: return SYSTEM_PROMPT + f"{message} [/INST]" formatted_message = SYSTEM_PROMPT + f"{history[0][0]} [/INST] {history[0][1]} </s>" # Handle conversation history for user_msg, model_answer in history[1:]: formatted_message += f"<s>[INST] {user_msg} [/INST] {model_answer} </s>" # Handle the current message formatted_message += f"<s>[INST] {message} [/INST]" return formatted_messageGenerate a response from the Llama model
def get_llama_response(message: str, history: list) -> str: """ Generates a conversational response from the Llama model.
Parameters: message (str): User's input message. history (list): Past conversation history. Returns: str: Generated response from the Llama model. """ query = format_message(message, history) response = "" sequences = llama_pipeline( query, do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=1024, ) generated_text = sequences[0]['generated_text'] response = generated_text[len(query):] # Remove the prompt from the output print("Chatbot:", response.strip()) return response.strip() - Assistant
- User
Use " instead of ”
- Assistant
Certainly! Below is the corrected code with standard double quotes for string literals:
!pip install transformers torch accelerate !pip install --upgrade gradio from transformers import AutoTokenizer, pipeline import torch import gradio as gr # Load tokenizer and model model = "meta-llama/Llama-2-7b-chat-hf" tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True) llama_pipeline = pipeline( "text-generation", model=model, torch_dtype=torch.float16, device_map="auto", ) # Initialize conversation history chat_history = [] def get_llama_response(message: str) -> str: global chat_history # Format the conversation history into the prompt SYSTEM_PROMPT = "<s>[INST] <<SYS>>\nYou are a helpful bot. Your answers are clear and concise.\n<</SYS>>\n" formatted_message = SYSTEM_PROMPT for turn in chat_history[-3:]: # Keep only the last 3 turns for brevity formatted_message += f"{turn}\n" formatted_message += f"{message} [/INST]</s>" # Generate and process the model's response sequences = llama_pipeline( formatted_message, do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=1024, ) generated_text = sequences[0]['generated_text'] response = generated_text[len(formatted_message):].strip() # Extract model's response # Append the last user message and chatbot response to history chat_history.append(f"User: {message}") chat_history.append(f"Chatbot: {response}") # Limit history to prevent very long prompts (this is arbitrary, adjust as needed) chat_history = chat_history[-6:] return response # Gradio interface iface = gr.Interface( fn=get_llama_response, # Response generation function inputs="text", # User input outputs="text", # Chatbot output allow_flagging="never", ) # Launch the interface iface.launch() - User
show the requirement.txt
- Assistant
The
requirements.txtfile lists the specific versions of Python packages that your project needs to run correctly. Here is an example of what yourrequirements.txtfile could look like for the chatbot project using Hugging Face's Transformers and Gradio, based on the code you've provided:transformers torch accelerate gradioHowever, you might also want to specify the exact versions you're using, to ensure that whoever sets up your project gets the same environment. To generate such a
requirements.txtwith specific versions, you can run the following shell command:!pip freeze > requirements.txtPlease note that this will list all installed packages and their versions in your current environment, which might be more than you need for your project.
For a more minimal approach, only including the key packages with versions, you could manually create your file with versions you've tested, like so:
- User
huggingface_hub.utils._headers.LocalTokenNotFoundError: Token is required (
token=True), but no token found. You need to provide a token or be logged in to Hugging Face withhuggingface-cli loginorhuggingface_hub.login. See https://huggingface.co/settings/tokens. - Assistant
The error message you're seeing indicates that the script you're running is trying to access the Hugging Face model through their API, and it requires an authentication token to do so. This is typically required when accessing models that are not public or when you have a private model on the Hugging Face Hub.
To resolve the
LocalTokenNotFoundError, follow these steps:- Visit the Hugging Face website and log in to your account.