File size: 1,383 Bytes
8957b2f 6bd508a 8957b2f 6bd508a 8957b2f 6bd508a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# Load model and tokenizer
model_name = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
def generate_response(message, history):
# Format the input with chat history
prompt = "".join([f"Human: {h[0]}\nAssistant: {h[1]}\n" for h in history])
prompt += f"Human: {message}\nAssistant:"
# Tokenize and generate
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1000, temperature=0.7, do_sample=True)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract only the assistant's response
assistant_response = response.split("Assistant:")[-1].strip()
return assistant_response
# Create the Gradio interface
iface = gr.ChatInterface(
generate_response,
title="Llama-2-7b Chat Interface",
description="Chat with the Llama-2-7b model. Type your message and press Enter.",
examples=[
"What is the capital of France?",
"Explain quantum computing in simple terms.",
"Write a short poem about artificial intelligence."
],
cache_examples=False,
)
# Launch the interface
iface.launch() |