To query models like Meta LLaMA 3.3 70B using a message-based format (often found in chat interfaces), you would typically structure your input as a list of messages, where each message has a role (e.g., "user", "assistant", or "system") and content.
If you're using a conversational interface, such as for a chatbot, you can set it up like this:
Revised Example with Message Structure
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Load the LLaMA model and tokenizer
model_name = "meta-llama/Llama-3.3-70B" # Make sure to use the correct model name
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
# Function to query the model
def query_model(messages, max_length=150):
# Prepare the input by joining messages into a single string
conversation = ""
for message in messages:
conversation += f"{message['role']}: {message['content']}\n"
inputs = tokenizer(conversation, return_tensors='pt').to(model.device)
# Generate output from the model
with torch.no_grad():
output = model.generate(**inputs, max_length=max_length)
# Decode and return the generated response
response = tokenizer.decode(output[0], skip_special_tokens=True)
# Optionally, you can split the response to get only the assistant's message
return response
# Set up the conversation history
messages = [
{
"role": "system",
"content": "You are a helpful assistant that provides information on various topics."
},
{
"role": "user",
"content": "What is deep learning?"
}
]
# Query the model
response = query_model(messages)
print("Assistant:", response)
Explanation:
-
Message Structure: The input messages list contains dictionaries with role and content keys, allowing for a structured conversation. The assistant will become more contextually aware of the ongoing conversation this way.
-
Building the Conversation Input: The query_model function builds a single string from the list of messages, formatting it appropriately, so it sends it to the model as input.
-
Model Response: The output is decoded and displayed as before. You can customize how you want to retrieve the assistant's response from the generated text.
Note:
Ensure your environment is set up to work with large models, and adjust the maximum length as needed based on how much of a response you're expecting. The actual handling of conversations and messages may vary based on your specific application and requirements.