I am trying to build a chatbot using llama model that run in vs code notebook locally,…
- User
I am trying to build a chatbot using llama model that run in vs code notebook locally, my code: import torch from transformers import AutoModelForCausalLM, AutoTokenizer
Path to your locally downloaded model directory model_path = r"C:\Users\shermanhonsf\Desktop\Python\llama_develop\model\Llama3.1-1B-Instruct-HF-Model"
Load the model and tokenizer tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForCausalLM.from_pretrained(model_path)
Check if CUDA (GPU) is available and move the model to GPU if so device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device)
Function to generate chatbot responses def generate_response(user_input, max_new_tokens=100, temperature=0.6, top_p=1):
Only pass the latest user input to the model inputs = tokenizer(f"User: {user_input}\nChatbot:", return_tensors="pt") input_ids = inputs["input_ids"].to(device) # Move input tensors to the GPU if available
Disable gradient calculation for faster performance since we are in inference mode with torch.no_grad(): output = model.generate( input_ids, max_new_tokens=max_new_tokens, temperature=temperature, #top_k=top_k, # Only consider the top_k options at each step top_p=top_p, # Nucleus sampling - the cumulative probability threshold pad_token_id=tokenizer.eos_token_id, # Token ID for padding do_sample=True # Use sampling for text generation )
Decode the generated tokens to text response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True) return response.strip() # Strip any leading or trailing whitespace Chatbot conversation loop def chat(): print("Chatbot is ready! Type 'exit' to stop the conversation.")
while True:
Get user input
user_input = input("You: ")
if user_input.lower() == "exit": print("Goodbye!") break
Generate response from the model
response = generate_response(user_input) print(f"Chatbot: {response}") if name == "main": chat()
However, the vs code notebook do not show real time output, so the output is only : Chatbot is ready! Type 'exit' to stop the conversation. Without input option. How to fix it?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.