I am writing the code to build a simple chat interface with the downloaded llm model:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
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_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# 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
code
# Generate the response using the model
with torch.no_grad():
output = model.generate(
input_ids,
max_length=max_length,
temperature=temperature,
top_k=top_k,
top_p=top_p,
pad_token_id=tokenizer.eos_token_id,
do_sample=True
)
# Decode the generated tokens to text
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip()
Chatbot conversation loop
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
code
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()
Help me to add # comment to explain the code.
Assistant
Certainly! Here's your code with comments explaining each part:
python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Path to your locally downloaded model directory
model_path = "/content/drive/MyDrive/model/Llama3.2-1B-Instruct-HF-Model"
# Load the tokenizer from the model directory
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Load the model from the model directory, specifically for causal language modeling
model = AutoModelForCausalLM.from_pretrained(model_path)
# Check if CUDA (GPU) is available. If yes, use GPU for computation to speed up the process
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Move the model to the appropriate device
model.to(device)
# Function to generate chatbot responses using the model
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# Tokenize the user input and prepare it for the model with special tokens
inputs = tokenizer(f"User: {user_input}\nChatbot:", return_tensors="pt")
# Move input tensors to the designated device (GPU or CPU)
input_ids = inputs["input_ids"].to(device)
# Disable gradient calculation for faster performance since we are in inference mode
with torch.no_grad():
# Generate the response from the model using various parameters for control
output = model.generate(
input_ids,
max_length=max_length, # Maximum length of the response
temperature=temperature, # Sampling temperature; higher means more variety
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 token IDs to a human-readable string
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip() # Strip any leading or trailing whitespace
# Function for a conversational loop with the chatbot
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
while True:
# Prompt the user for input
user_input = input("You: ")
# Check if the user wants to exit the conversation
if user_input.lower() == "exit":
print("Goodbye!")
break
# Generate a response from the model based on user input
response = generate_response(user_input)
# Print the chatbot's response
print(f"Chatbot: {response}")
# Start the chat when the script is executed
if __name__ == "__main__":
chat()
User
In inputs = tokenizer(f"User: {user_input}\nChatbot:", return_tensors="pt")
what is return_tensors="pt"?
The argument return_tensors="pt" specifies the format in which you want the tokenized output. Here, "pt" stands for PyTorch, indicating that you want the output to be in PyTorch tensor format.
When you use return_tensors="pt", the tokenizer will return the inputs as PyTorch tensors, which are suitable for direct input into a PyTorch model (like the one you're using from the transformers library). This is especially useful when you want to perform operations on the data using PyTorch, as it allows seamless integration with PyTorch's functionality for deep learning models.
In summary, return_tensors="pt" ensures that the tokenized outputs are returned as PyTorch tensors. If you are using TensorFlow, you might use return_tensors="tf" instead to get TensorFlow tensors.
User
OK, from the above code, how to control the length of the model output each time?
Assistant
In your code, the length of the model's output can be controlled by adjusting the max_length parameter in the generate_response function. This parameter sets the maximum number of tokens (words, punctuation marks, and other meaningful elements) that the model can generate in response to a given input.
Here’s the relevant section of the code:
python
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
...
# Generate the response using the model
with torch.no_grad():
output = model.generate(
input_ids,
max_length=max_length, # Maximum length of the response
temperature=temperature,
top_k=top_k,
top_p=top_p,
pad_token_id=tokenizer.eos_token_id,
do_sample=True
)
...
Adjusting Output Length:
Decrease the max_length:
If you want shorter responses, reduce the max_length parameter. This limits how many tokens the model can generate, effectively shortening its replies.
Increase the max_length:
If you want longer responses, increase the max_length parameter to allow the model to generate more tokens.
Example:
If you find that the responses are too long and you want them to be approximately 100 tokens:
Remember, the actual length of the response can vary slightly due to how the model decides to end sentences, and it might also stop sooner if it predicts an end-of-sequence token. Adjusting max_length sets an upper bound but doesn't guarantee that all responses will be exactly that length.
User
Code:
"
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
Load the model from the model directory, specifically for causal language modeling
model = AutoModelForCausalLM.from_pretrained(model_path)
Check if CUDA (GPU) is available. If yes, use GPU for computation to speed up the process
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Move the model to the appropriate device
model.to(device)
Function to generate chatbot responses using the model
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# Tokenize the user input and prepare it for the model with special tokens
inputs = tokenizer(f"User: {user_input}\nChatbot:", return_tensors="pt")
# Move input tensors to the designated device (GPU or CPU)
input_ids = inputs["input_ids"].to(device)
code
# Disable gradient calculation for faster performance since we are in inference mode
with torch.no_grad():
# Generate the response from the model using various parameters for control
output = model.generate(
input_ids,
max_length=max_length, # Maximum length of the response
temperature=temperature, # Sampling temperature; higher means more variety
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 token IDs to a human-readable string
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip() # Strip any leading or trailing whitespace
Assistant
To incorporate a system prompt or an initial context in the chatbot, you can modify how the input text is prepared before being sent to the model. A system prompt is a predefined string that sets the tone, context, or instructions for the conversation. You can prepend this prompt to the user's input when generating a response.
Here's how you could integrate a system prompt into your code:
Define a System Prompt:
First, decide on the message or context you want to establish. This could be something like "This is a helpful AI assistance system.".
Incorporate the System Prompt:
Include the system prompt when preparing the input for the model in the generate_response function.
Here's how you can modify your existing code to include a system prompt:
python
User
Is it the correct prompt format? You can refer to the following:
Model Cards & Prompt formats
Llama 3.1
Introduction
This page describes the prompt format for Llama 3.1 with an emphasis on new features in that release.
With the subsequent release of Llama 3.2, we have introduced new lightweight models in 1B and 3B and also multimodal models in 11B and 90B. The first few sections of this page--Prompt Template, Base Model Prompt, and Instruct Model Prompt--are applicable across all the models released in both Llama 3.1 and Llama 3.2.
Please leverage this guidance in order to take full advantage of the new Llama models. Although prompts designed for Llama 3 should work unchanged in Llama 3.1 and Llama 3.2, we recommend that you update your prompts to the new format to obtain the best results.
Model Card
For comprehensive technical information about the Llama 3.1 collection of large-language models, please see the official model card, located on GitHub.
Prompt Template
Special Tokens
Tokens
Description
<|begin_of_text|>
Specifies the start of the prompt.
<|end_of_text|>
Model will cease to generate more tokens. This token is generated only by the base models.
<|finetune_right_pad_id|>
This token is used for padding text sequences to the same length in a batch.
<|start_header_id|>
<|end_header_id|>
These tokens enclose the role for a particular message. The possible roles are: [system, user, assistant, and ipython]
<|eom_id|>
End of message. A message represents a possible stopping point for execution where the model can inform the executor that a tool call needs to be made. This is used for multi-step interactions between the model and any available tools. This token is emitted by the model when the Environment: ipython instruction is used in the system prompt, or if the model calls for a built-in tool.
<|eot_id|>
End of turn. Represents when the model has determined that it has finished interacting with the user message that initiated its response. This is used in two scenarios:
at the end of a direct interaction between the model and the user
at the end of multiple interactions between the model and any available tools
This token signals to the executor that the model has finished generating a response.
<|python_tag|>
Special tag used in the model’s response to signify a tool call.
Supported Roles
There are 4 different roles that are supported by Llama text models:
system: Sets the context in which to interact with the AI model. It typically includes rules, guidelines, or necessary information that help the model respond effectively.
user: Represents the human interacting with the model. It includes the inputs, commands, and questions to the model.
ipython: A new role introduced in Llama 3.1. Semantically, this role means "tool". This role is used to mark messages with the output of a tool call when sent back to the model from the executor.
assistant: Represents the response generated by the AI model based on the context provided in the system, ipython and user prompts.
[system, assistant, user, ipython]
Pretrained Model Prompt
This is the simplest way to prompt llama-based models, starting with text and allowing the model to generate new content based on the user-provided input.
Assistant
Given the detailed information you've provided about prompt formats and special tokens used in the Llama models, it's important to adapt the prompt input to match these formats to get the best results from your Llama 3.2 model.
The correct prompt format helps the model understand the roles of different parts of the input (system, user, assistant, etc.) and helps guide the conversation. Here's how you can format your prompts based on the information you've given:
Define a System Message:
Use it to set the AI model's identity and purpose along with any necessary environment information.
Structure the Prompts Using Special Tokens:
Make use of <|begin_of_text|>, <|start_header_id|>, <|end_header_id|>, <|eot_id|> to structure your complete prompt as defined in the format guidelines.
Here's how you can modify your code to integrate these concepts:
python
User
For llama 3.2:
Llama 3.2 Lightweight Models (1B/3B)
Model Card (1B/3B)
For comprehensive technical information about the Llama 3.2 collection of Lightweight models, please see the official model card, located on GitHub.
Inference with lightweight models
The recommended way to run inference for these lightweight models on-device is using the PyTorch ExecuTorch framework. ExecuTorch is an end-to-end solution for enabling on-device inference capabilities across mobile and edge devices including wearables, embedded devices and microcontrollers. It is part of the PyTorch Edge ecosystem and enables efficient deployment of various PyTorch models (vision, speech, Generative AI, and more) to edge devices.
To support our lightweight model launches, ExecuTorch is now supporting bfloat16 with the XNNPack backend in both Android and iOS, please check out our repository on Github for more technical details as well as end-to-end tutorials.
In addition to the bfloat16 models described above, Llama 3.2 also includes quantized versions of the 1B and 3B models. For more information about these quantized versions, see this section.
Prompt Template
The lightweight models share many characteristics with the Llama 3.1 text-only models. For information that is applicable across both sets of models, see the following sections on the Llama 3.1 page.
Special Tokens
Supported Roles
Llama 3.1 Pretrained
Llama 3.1 Instruct
Code Interpreter
Tool Calling (1B/3B)
Tool-calling with the lightweight models can be done in 2 ways:
Pass the function definitions in the system prompt + pass the query in the user prompt
Pass the function definitions and query in the user prompt
Note: Unlike the Llama 3.1 larger Models (8B/70B/405B), the lightweight models do not support built-in tools (Brave Search and Wolfram). The lightweight models only support custom functions defined in either the system prompt or user prompt. This decision was made to simplify the user experience of tool-calling with our lightweight models.
Function definitions in the system prompt
Set the function definitions
function_definitions = """[
{
"name": "get_user_info",
"description": "Retrieve details for a specific user by their unique identifier. Note that the provided function is in Python 3 syntax.",
"parameters": {
"type": "dict",
"required": [
"user_id"
],
"properties": {
"user_id": {
"type": "integer",
"description": "The unique identifier of the user. It is used to fetch the specific user details from the database."
},
"special": {
"type": "string",
"description": "Any special information or parameters that need to be considered while fetching user details.",
"default": "none"
}
}
}
}
]
"""
Set the default system prompt
system_prompt = """You are an expert in composing functions. You are given a question and a set of possible functions.
Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
If none of the function can be used, point it out. If the given question lacks the parameters required by the function,
also point it out. You should only return the function call in tools call sections.
Assistant
To incorporate the detailed prompt format and function calling methods provided for Llama 3.2 lightweight models into your script, you can follow the recommended prompt structures for engaging with the model. Here’s how you can set this up in your existing code to utilize the lightweight model effectively:
Step-by-Step Integration:
Define Function Definitions: Create a JSON structure for the functions that the model can invoke. This is usually done in the system prompt.
Create System and User Prompts: Construct the prompts using the special tokens and guidelines provided for defining roles and expectations.
Generate and Handle Model Responses: Using the prompt setup, the model will generate responses formatted as function calls. You can extract these responses for execution.
Here’s a code example implementing this:
python
User
can i use InferenceClient for this downloaded model?
Assistant
The InferenceClient is typically designed for connecting with remote models served on a dedicated inference API or server rather than directly with a locally downloaded model. If you're working with Hugging Face's transformers library and local model files, InferenceClient is not directly applicable for local inference.
Typical Use of InferenceClient
InferenceClient is often used to connect to services like Hugging Face's Inference API, where you send requests to the Hugging Face endpoint, and the model is run on Hugging Face's infrastructure. It's designed for:
Remote Inference: Interacting with models hosted on cloud services.
Simplified API Requests: Sending inputs and receiving outputs without handling the model deployment complexities.
Options for Local Model Inference
For locally downloaded models, you typically use PyTorch or TensorFlow directly, along with the transformers library, like this:
Transformers with PyTorch/TensorFlow:
Load models and tokenizers using transformers.AutoModelForCausalLM and transformers.AutoTokenizer.
Perform inference using model.generate() or similar methods directly on your local hardware.
ExecuTorch (for Edge Devices):
If targeting edge devices and mobile inference, you may explore leveraging frameworks like ExecuTorch, as outlined in the Llama 3.2 documentation.
This involves converting models to formats and frameworks suitable for edge deployment and performance-critical environments.
Conclusion
If you intend to continue using a local setup:
Stick with the PyTorch (transformers library) method for inference.
This approach gives you complete control over the model use, customization in pre- and post-processing, and local resource utilization.
If you aim to integrate with an inference API (hosted remotely), look for specific documentation such as the Inference API provided by the model host for correct usage and avoid reliance on InferenceClient for local model integration.
These comments should help you understand the purpose and function of each part of the script.
Function for a conversational loop with the chatbot
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
code
while True:
# Prompt the user for input
user_input = input("You: ")
# Check if the user wants to exit the conversation
if user_input.lower() == "exit":
print("Goodbye!")
break
# Generate a response from the model based on user input
response = generate_response(user_input)
# Print the chatbot's response
print(f"Chatbot: {response}")
Start the chat when the script is executed
if name == "main":
chat()
"
OK, from the above code, how to add the system prompt?
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Path to your locally downloaded model directory
model_path = "/content/drive/MyDrive/model/Llama3.2-1B-Instruct-HF-Model"
# Load the tokenizer from the model directory
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Load the model from the model directory, specifically for causal language modeling
model = AutoModelForCausalLM.from_pretrained(model_path)
# Check if CUDA (GPU) is available. If yes, use GPU for computation to speed up the process
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Move the model to the appropriate device
model.to(device)
# Define a system prompt for setting context
system_prompt = "This is a helpful AI assistant."
# Function to generate chatbot responses using the model
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# Incorporate the system prompt along with user input
full_input = f"{system_prompt}\nUser: {user_input}\nChatbot:"
# Tokenize the complete input and prepare it for the model with special tokens
inputs = tokenizer(full_input, return_tensors="pt")
# Move input tensors to the designated device (GPU or CPU)
input_ids = inputs["input_ids"].to(device)
# Disable gradient calculation for faster performance since we are in inference mode
with torch.no_grad():
# Generate the response from the model using various parameters for control
output = model.generate(
input_ids,
max_length=max_length, # Maximum length of the response
temperature=temperature, # Sampling temperature; higher means more variety
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 token IDs to a human-readable string
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip() # Strip any leading or trailing whitespace
# Function for a conversational loop with the chatbot
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
while True:
# Prompt the user for input
user_input = input("You: ")
# Check if the user wants to exit the conversation
if user_input.lower() == "exit":
print("Goodbye!")
break
# Generate a response from the model based on user input
response = generate_response(user_input)
# Print the chatbot's response
print(f"Chatbot: {response}")
# Start the chat when the script is executed
if __name__ == "__main__":
chat()
By adding system_prompt at the beginning of each input, the model can maintain the context or style you want throughout the conversation. Adjust the text of system_prompt to match the desired context or instructions for your chatbot.
<|begin_of_text|>{{ user_message}}
Instruct Model Prompt
The format for a regular multi-turn conversation between a user and the model has not changed between Llama 3 and Llama 3.1. Here is a simple example of how it's formatted.
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
You are a helpful assistant<|eot_id|><|start_header_id|>user<|end_header_id|>
What is the capital of France?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
For more examples of the prompt template, please refer to text_prompt_format.md in the meta-llama GitHub repository.
Code Interpreter
The code interpreter feature allows the model to generate executable Python code in response to the user query. The code interpreter is triggered when Environment: ipython is included in the system prompt.
Notes
The model’s response is wrapped in a <|python_tag|> and terminated with an <|eom_id|> tag.
The <|eom_id|> indicates a continued multi-step reasoning. That is, the model is expecting a continuation message with the output of the tool call.
Sample Input:
Write code to check if number is prime, use that to see if the number 7 is prime<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Response:
<|python_tag|>def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7)) # Output: True<|eom_id|>
Note that the model itself does not execute the code output; you need to use our llama-stack-apps, or other similar framework to leverage code interpreters. When using llama-stack-apps, the results of the code are passed back to the model for further processing.
Tool Calling (8B/70B/405B)
Tool-calling with the larger models can be done in three ways:
Built-in Tools (Brave, Wolfram)
JSON-based Tool Calling
User-defined Custom Tool Calling
Note: We recommend using Llama 70B-instruct or Llama 405B-instruct for applications that combine conversation and tool calling. Llama 8B-Instruct can not reliably maintain a conversation alongside tool calling definitions. It can be used for zero-shot tool calling, but tool instructions should be removed for regular conversations between the model and the user.
Defining multiple tools in the system and/or user prompt can cause the model to generate multiple tool calls as a result of the user query. Developers must iterate on the prompts required to get the desired result and parse the result accordingly.
To better illustrate the flows below, this diagram shows the flow of information described:
Flow diagram
User and assistant conversation
The format for a regular multi-turn conversation between a user and the model has not changed between Llama 3 and Llama 3.1. Here is a simple example of how it's formatted.
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
You are a helpful assistant<|eot_id|><|start_header_id|>user<|end_header_id|>
What is the capital of France?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Built in Python based tool calling
The models are trained to use two built-in tools:
Brave Search: Tool call to perform web searches.
Wolfram Alpha: Tool call to perform complex mathematical calculations.
These can be turned on using the system prompt:
Environment: ipython
Tools: brave_search, wolfram_alpha
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
You are a helpful assistant<|eot_id|>
<|start_header_id|>user<|end_header_id|>
What is the current weather in Menlo Park, California?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
A few things to note:
Just including Environment: ipython turns on code interpreter; therefore, you don’t need to specify code interpretation on the Tools: line. The model can generate python code which is interpreted by the executor, with the result provided back to the model.
The message body of the assistant response starts with a special tag <|python_tag|>
As alluded to above, in such an environment, the model can generate <|eom_id|> instead of just the standard <|eot_id|> . The latter indicates the turn is finished, while the former indicates continued multi-step reasoning. That is, the model is expecting a continuation message with the output of the tool call.
The built-in tool is called using python syntax, and not JSON format as for zero-shot tools. The python call that the model generates for each of the tools is of the form:
<|python_tag|>
wolfram_alpha.call(query="...")
<|eom_id|>
To create custom tool calls using the zero-shot learning capability of the model, you can provide instructions for the tool definition in the system prompt along with the format you want the model to produce for the call. A working example is provided in the llama-agentic-system GitHub repository. You can check it out here.
The example below shows an end-to-end interaction of prompts between the user ⇔ model ⇔ tool. This sample system uses the wolfram_alpha in-built tool. (Please note: The model does not execute the call to the tool; you need to use our llama-agentic-system, or other similar framework, to leverage the tool-calling capabilities.)
Step - 1 User Prompt & System prompts
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Environment: ipython
Tools: brave_search, wolfram_alpha
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
Can you help me solve this equation: x^3 - 4x^2 + 6x - 24 = 0<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 2 Model determining which tool to call
<|python_tag|>wolfram_alpha.call(query="solve x^3 - 4x^2 + 6x - 24 = 0")<|eom_id|>
Step - 3 Response generated by tool, that is, Wolfram Alpha.
{
"queryresult": {
"success": true,
"inputstring": "solve x^3 - 4x^2 + 6x - 24 = 0",
"pods": [
{
"title": "Input interpretation",
"subpods": [
{
"title": "",
"plaintext": "solve x^3 - 4 x^2 + 6 x - 24 = 0"
}
]
},
{
"title": "Results",
"primary": true,
"subpods": [
{
"title": "",
"plaintext": "x = 4"
},
{
"title": "",
"plaintext": "x = ± (i sqrt(6))"
}
]
},
...
]
}
}
Step - 4 Reprompt Model with tool response
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Environment: ipython
Tools: brave_search, wolfram_alpha
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
Can you help me solve this equation: x^3 - 4x^2 + 6x - 24 = 0<|eot_id|><|start_header_id|>assistant<|end_header_id|>
{"queryresult": {"success": true, "inputstring": "solve x^3 - 4x^2 + 6x - 24 = 0", "pods": [{"title": "Input interpretation", "subpods": [{"title": "", "plaintext": "solve x^3 - 4 x^2 + 6 x - 24 = 0"}]}, {"title": "Results", "primary": true, "subpods": [{"title": "", "plaintext": "x = 4"}, {"title": "", "plaintext": "x = \u00b1 (i sqrt(6))"}]}, ... ]}}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 5 Response from Agent to User
The solutions to the equation x^3 - 4x^2 + 6x - 24 = 0 are x = 4 and x = ±(i√6).<|eot_id|>
JSON based tool calling
Meta Llama models can now output custom tool calls from a single message to allow easier tool calling. The following prompts provide an example of how custom tools can be called from the output of the model. It's important to note that the model itself does not execute the calls; it provides structured output to facilitate calling by an executor. An example executor can be found in the llama-agentic-system. The tool format is similar to the OpenAI definition and can be adjusted to better suit your needs, as noted in the following section.
Notes
With custom tool calling, for the model to output the eom_id, the following instruction needs to be added to the system prompt: Environment: ipython. Else, it should output eot_id.
The system prompt needs to be adjusted to inform the model how to deal with tool call outputs
The tool definition is provided in the user prompt, as that is how the model was trained for the built in JSON tool calling. However, it's possible to provide the tool definition in the system prompt as well—and get similar results. Developers must test which way works best for their use case.
Step - 1 User prompt with custom tool details
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
When you receive a tool call response, use the output to format an answer to the orginal user question.
You are a helpful assistant with tool calling capabilities.<|eot_id|><|start_header_id|>user<|end_header_id|>
Given the following functions, please respond with a JSON for a function call with its proper arguments that best answers the given prompt.
Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. Do not use variables.
{
"type": "function",
"function": {
"name": "get_current_conditions",
"description": "Get the current weather conditions for a specific location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g., San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["Celsius", "Fahrenheit"],
"description": "The temperature unit to use. Infer this from the user's location."
}
},
"required": ["location", "unit"]
}
}
}
Question: what is the weather like in San Fransisco?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 2 Model determining which tool to call
Note:
As we are not using the Environment: ipython instruction in the system prompt, the model ends generation with the eot_id token, not the eom_id token
{"name": "get_current_conditions", "parameters": {"location": "San Francisco, CA", "unit": "Fahrenheit"}}<eot_id>
Step - 3 Result from calling the tool is passed back to the model
When the result of the tool call is sent back to the model, we use the new role, ipython, in the header.
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
You are a helpful assistant with tool calling capabilities. When you receive a tool call response, use the output to format an answer to the orginal use question.<|eot_id|><|start_header_id|>user<|end_header_id|>
Given the following functions, please respond with a JSON for a function call with its proper arguments that best answers the given prompt.
Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. Do not use variables.
{
"type": "function",
"function": {
"name": "get_current_conditions",
"description": "Get the current weather conditions for a specific location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g., San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["Celsius", "Fahrenheit"],
"description": "The temperature unit to use. Infer this from the user's location."
}
},
"required": ["location", "unit"]
}
}
}
Question: what is the weather like in San Fransisco?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
{"output": "Clouds giving way to sun Hi: 76° Tonight: Mainly clear early, then areas of low clouds forming Lo: 56°"}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 4 The model generates the final response the user
The weather in Menlo Park is currently cloudy with a high of 76° and a low of 56°, with clear skies expected tonight.<eot_id>
User-defined Custom tool calling
The following prompts provide an example of how to define your own format in the system prompt and make use of it while interacting with the model. This format will use a new and custom tag to enclose a JSON object with the function parameters.
Notes
The model uses the eom_id token because of the Environment: ipython instruction.
The system prompt defines the custom format as well as the tools the model has available.
Step - 1 System prompt with custom tool details
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Environment: ipython
Tools: brave_search, wolfram_alpha
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
Tool Instructions
Always execute python code in messages that you share.
When looking for real time information use relevant functions if available else fallback to brave_search
You have access to the following functions:
Use the function 'spotify_trending_songs' to: Get top trending songs on Spotify
{
"name": "spotify_trending_songs",
"description": "Get top trending songs on Spotify",
"parameters": {
"n": {
"param_type": "int",
"description": "Number of trending songs to get",
"required": true
}
}
}
If a you choose to call a function ONLY reply in the following format:
<{start_tag}={function_name}>{parameters}{end_tag}
where
start_tag => <function
parameters => a JSON dict with the function argument name as key and function argument value as value.
end_tag => </function>
Here is an example,
<function=example_function_name>{"example_name": "example_value"}
Reminder:
Function calls MUST follow the specified format
Required parameters MUST be specified
Only call one function at a time
Put the entire function call reply on one line
Always add your sources when using search results to answer the user query
You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
Can you check the top 5 trending songs on spotify?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 2 Model determining which tool to call
Now the model responds in accordance with the format defined in the system prompt, with the function name in the start tag, and the parameters, as a JSON object, in between the start and end tags.
Note:
As we are using the Environment: ipython instruction in the system prompt, the model ends generation with the eom_id token.
<function=spotify_trending_songs>{"n": "5"}<eom_id>
Step - 3 Result from calling the tool is passed back to the model
When the result of the tool call is sent back to the model, we use the new role, ipython, in the header.
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Environment: ipython
Tools: brave_search, wolfram_alpha
Cutting Knowledge Date: December 2023
Today Date: 23 July 2024
Tool Instructions
Always execute python code in messages that you share.
When looking for real time information use relevant functions if available else fallback to brave_search
You have access to the following functions:
Use the function 'spotify_trending_songs' to: Get top trending songs on Spotify
{"name": "spotify_trending_songs", "description": "Get top trending songs on Spotify", "parameters": {"n": {"param_type": "int", "description": "Number of trending songs to get", "required": true}}}
If a you choose to call a function ONLY reply in the following format:
<{start_tag}={function_name}>{parameters}{end_tag}
where
start_tag => <function
parameters => a JSON dict with the function argument name as key and function argument value as value.
end_tag => </function>
Here is an example,
<function=example_function_name>{"example_name": "example_value"}
Reminder:
Function calls MUST follow the specified format
Required parameters MUST be specified
Only call one function at a time
Put the entire function call reply on one line
Always add your sources when using search results to answer the user query
You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
Can you check the top 5 trending songs on spotify?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
["1. BIRDS OF A FEATHER by Billie Eilish", "2. Espresso by Sabrina Carpenter", "3. Please Please Please by Sabrina Carpenter", "4. Not Like Us by Kendrick Lamar", "5. Gata Only by FloyyMenor, Cris Mj"]<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Step - 4 The model generates the final response the user
The top 5 trending songs on Spotify are:
BIRDS OF A FEATHER by Billie Eilish
Espresso by Sabrina Carpenter
Please Please Please by Sabrina Carpenter
Not Like Us by Kendrick Lamar
Gata Only by FloyyMenor, Cris Mj<|eot_id|>
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Path to your locally downloaded model directory
model_path = "/content/drive/MyDrive/model/Llama3.2-1B-Instruct-HF-Model"
# Load the tokenizer from the model directory
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Load the model from the model directory, specifically for causal language modeling
model = AutoModelForCausalLM.from_pretrained(model_path)
# Check if CUDA (GPU) is available. If yes, use GPU for computation to speed up the process
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Move the model to the appropriate device
model.to(device)
# Define a system prompt using special tokens to set the initial context
system_prompt = (
"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n"
"You are a helpful AI assistant.\n"
"<|eot_id|>"
)
# Function to generate chatbot responses using the model
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# Incorporate the system prompt and format user input
full_input = (
f"{system_prompt}"
f"<|start_header_id|>user<|end_header_id|>\n"
f"{user_input}\n<|eot_id|>"
f"<|start_header_id|>assistant<|end_header_id|>"
)
# Tokenize the complete input and prepare it for the model with special tokens
inputs = tokenizer(full_input, return_tensors="pt")
# Move input tensors to the designated device (GPU or CPU)
input_ids = inputs["input_ids"].to(device)
# Disable gradient calculation for faster performance since we are in inference mode
with torch.no_grad():
# Generate the response from the model using various parameters for control
output = model.generate(
input_ids,
max_length=max_length, # Maximum length of the response
temperature=temperature, # Sampling temperature; higher means more variety
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 token IDs to a human-readable string
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip() # Strip any leading or trailing whitespace
# Function for a conversational loop with the chatbot
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
while True:
# Prompt the user for input
user_input = input("You: ")
# Check if the user wants to exit the conversation
if user_input.lower() == "exit":
print("Goodbye!")
break
# Generate a response from the model based on user input
response = generate_response(user_input)
# Print the chatbot's response
print(f"Chatbot: {response}")
# Start the chat when the script is executed
if __name__ == "__main__":
chat()
Key Adjustments:
Conduct Role Assignment: Use <|start_header_id|> and <|end_header_id|> to mark the beginning and end of specific roles, e.g., system, user, assistant.
Structure the Text: Start with <|begin_of_text|>, use <|eot_id|> to represent the end of the turn.
System Prompt: Define the behavior and role of the AI in the system_prompt.
This setup should help you effectively use your model in line with Llama 3.1 and 3.2's prompt format requirements.
If you decide to invoke any of the function(s), you MUST put it in the format of [func_name1(params_name1=params_value1, params_name2=params_value2...), func_name2(params)]\n
You SHOULD NOT include any other text in the response.
Here is a list of functions in JSON format that you can invoke.\n\n{functions}\n""".format(functions=function_definitions)
Set the user query
query = "Can you retrieve the details for the user with the ID 7890, who has black as their special request?"
With the above function definition, system prompt and user query, the input to the LLM looks like:
<|start_header_id|>system<|end_header_id|>
You are an expert in composing functions. You are given a question and a set of possible functions.
Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
If none of the functions can be used, point it out. If the given question lacks the parameters required by the function,also point it out. You should only return the function call in tools call sections.
If you decide to invoke any of the function(s), you MUST put it in the format of [func_name1(params_name1=params_value1, params_name2=params_value2...), func_name2(params)]
You SHOULD NOT include any other text in the response.
Here is a list of functions in JSON format that you can invoke.[
{
"name": "get_user_info",
"description": "Retrieve details for a specific user by their unique identifier. Note that the provided function is in Python 3 syntax.",
"parameters": {
"type": "dict",
"required": [
"user_id"
],
"properties": {
"user_id": {
"type": "integer",
"description": "The unique identifier of the user. It is used to fetch the specific user details from the database."
},
"special": {
"type": "string",
"description": "Any special information or parameters that need to be considered while fetching user details.",
"default": "none"
}
}
}
}
]
<|eot_id|><|start_header_id|>user<|end_header_id|>
Can you retrieve the details for the user with the ID 7890, who has black as their special request?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
And the model responds with the function call that can fulfill the user’s query:
[get_user_info(user_id=7890, special='black')]<|eot_id|>
Function definitions and query in the user prompt
You could pass everything in the user prompt as well:
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
Questions: Can you retrieve the details for the user with the ID 7890, who has black as their special request?
Here is a list of functions in JSON format that you can invoke:
[
{
"name": "get_user_info",
"description": "Retrieve details for a specific user by their unique identifier. Note that the provided function is in Python 3 syntax.",
"parameters": {
"type": "dict",
"required": [
"user_id"
],
"properties": {
"user_id": {
"type": "integer",
"description": "The unique identifier of the user. It is used to fetch the specific user details from the database."
},
"special": {
"type": "string",
"description": "Any special information or parameters that need to be considered while fetching user details.",
"default": "none"
}
}
}
}
]
Should you decide to return the function call(s), Put it in the format of [func1(params_name=params_value, params_name2=params_value2...), func2(params)]
NO other text MUST be included.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
With the same response:
[get_user_info(user_id=7890, special='black')]<|eot_id|>
Note that the model’s response ends with an <|eot_id|> tag indicating end of turn.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Path to your locally downloaded model directory
model_path = "/content/drive/MyDrive/model/Llama3.2-1B-Instruct-HF-Model"
# Load the tokenizer and model from the model directory
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path)
# Use GPU if available for faster processing
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Define function schema in JSON format
function_definitions = """[
{
"name": "get_user_info",
"description": "Retrieve details for a specific user by their unique identifier. Note that the provided function is in Python 3 syntax.",
"parameters": {
"type": "dict",
"required": [
"user_id"
],
"properties": {
"user_id": {
"type": "integer",
"description": "The unique identifier of the user. It is used to fetch the specific user details from the database."
},
"special": {
"type": "string",
"description": "Any special information or parameters that need to be considered while fetching user details.",
"default": "none"
}
}
}
}
]
"""
# Set up the system prompt with the function information
system_prompt = (
"<|start_header_id|>system<|end_header_id|>\n"
"You are an expert in composing functions. You are given a question and a set of possible functions. "
"Based on the question, you will need to make one or more function/tool calls to achieve the purpose. "
"If none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out. "
"You should only return the function call in tools call sections.\n"
"If you decide to invoke any of the function(s), you MUST put it in the format of [func_name1(params_name1=params_value1, params_name2=params_value2...), func_name2(params)]\n"
"You SHOULD NOT include any other text in the response.\n\n"
"Here is a list of functions in JSON format that you can invoke.\n\n{functions}\n<|eot_id|>"
).format(functions=function_definitions)
# Function to generate chatbot responses with function calling
def generate_response(user_input, max_length=1000, temperature=0.7, top_k=50, top_p=0.95):
# Append user input to the system prompt
full_input = (
f"{system_prompt}"
f"<|start_header_id|>user<|end_header_id|>\n"
f"{user_input}\n<|eot_id|><|start_header_id|>assistant<|end_header_id|>"
)
# Tokenize the complete input using the special tokens
inputs = tokenizer(full_input, return_tensors="pt")
input_ids = inputs["input_ids"].to(device)
# Model generates the response based on provided input
with torch.no_grad():
output = model.generate(
input_ids,
max_length=max_length,
temperature=temperature,
top_k=top_k,
top_p=top_p,
pad_token_id=tokenizer.eos_token_id,
do_sample=True
)
# Decode the generated output to a manageable format
response = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
return response.strip()
# Function for user interaction
def chat():
print("Chatbot is ready! Type 'exit' to stop the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
print("Goodbye!")
break
response = generate_response(user_input)
print(f"Chatbot: {response}")
# Main execution
if __name__ == "__main__":
chat()
Key Points:
System Prompt with Function Definitions: Sets function details and guidelines for how the model should output responses.
Structured User Querying: Ensure queries are formatted to match the expectation laid out in the system prompt.
Response Handling: Processes the model's function call outputs for any required task executions.
By following this layout and the Llama 3.2 guidelines, you can leverage the model's function-calling capabilities effectively. Adjust the system and user prompts as necessary based on your specific use case.