This repo contains State Of The Art quantized GGUF format model files for Gorilla OpenFunctions v2.
Quantization was done with an importance matrix that was trained for ~1M tokens (256 batches of 4096 tokens) of training data from gorilla_openfunctions_v1_train.json.
Everything has been reconverted and quantized with a new importance matrix using llama.cpp from April 29th 2024 onwards, as of commit f4ab2a4 to ensure correct pre-tokenization. The new GGUFs will work with older llama.cpp, but this may not generate correct prompt tokens, please use a recent build to ensure the best possible results!
Prompt template: Gorilla OpenFunctions v2
You are an AI programming assistant, utilizing the Gorilla LLM model, developed by Gorilla LLM, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction: <<function>>[{"name": "function_name", "description": "Description", "parameters": {...}}, ...]
<<question>>{prompt}
### Response:
Compatibility
These quantised GGUFv3 files are compatible with llama.cpp from February 27th 2024 onwards, as of commit 0becb22
They are also compatible with many third party UIs and libraries provided they are built using a recent llama.cpp.
Explanation of quantisation methods
Click to see details
The new methods available are:
GGML_TYPE_IQ1_S - 1-bit quantization in super-blocks with an importance matrix applied, effectively using 1.56 bits per weight (bpw)
GGML_TYPE_IQ1_M - 1-bit quantization in super-blocks with an importance matrix applied, effectively using 1.75 bpw
GGML_TYPE_IQ2_XXS - 2-bit quantization in super-blocks with an importance matrix applied, effectively using 2.06 bpw
GGML_TYPE_IQ2_XS - 2-bit quantization in super-blocks with an importance matrix applied, effectively using 2.31 bpw
GGML_TYPE_IQ2_S - 2-bit quantization in super-blocks with an importance matrix applied, effectively using 2.5 bpw
GGML_TYPE_IQ2_M - 2-bit quantization in super-blocks with an importance matrix applied, effectively using 2.7 bpw
GGML_TYPE_IQ3_XXS - 3-bit quantization in super-blocks with an importance matrix applied, effectively using 3.06 bpw
GGML_TYPE_IQ3_XS - 3-bit quantization in super-blocks with an importance matrix applied, effectively using 3.3 bpw
GGML_TYPE_IQ3_S - 3-bit quantization in super-blocks with an importance matrix applied, effectively using 3.44 bpw
GGML_TYPE_IQ3_M - 3-bit quantization in super-blocks with an importance matrix applied, effectively using 3.66 bpw
GGML_TYPE_IQ4_XS - 4-bit quantization in super-blocks with an importance matrix applied, effectively using 4.25 bpw
GGML_TYPE_IQ4_NL - 4-bit non-linearly mapped quantization with an importance matrix applied, effectively using 4.5 bpw
Refer to the Provided Files table below to see what files use which methods, and how.
Note: the above RAM figures assume no GPU offloading with 4K context. If layers are offloaded to the GPU, this will reduce RAM usage and use VRAM instead.
Example llama.cpp command
Make sure you are using llama.cpp from commit 0becb22 or later.
./main -ngl 33 -m gorilla-openfunctions-v2.IQ3_M.gguf --color -c 16384 --temp 0 --repeat-penalty 1.1 -p "You are an AI programming assistant, utilizing the Gorilla LLM model, developed by Gorilla LLM, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction: <<function>>{functions}\n<<question>>{prompt}\n### Response: "
Change -ngl 33 to the number of layers to offload to GPU. Remove it if you don't have GPU acceleration.
Change -c 16384 to the desired sequence length.
If you want to have a chat-style conversation, replace the -p <PROMPT> argument with -i -ins
If you are low on V/RAM try quantizing the K-cache with -ctk q8_0 or even -ctk q4_0 for big memory savings (depending on context size).
There is a similar option for V-cache (-ctv), however that is not working yet.
Run one of the following commands, according to your system:
shell
1# Prebuilt wheel with basic CPU support2pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
3# Prebuilt wheel with NVidia CUDA acceleration4pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121 (or cu122 etc.)5# Prebuilt wheel with Metal GPU acceleration6pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/metal
7# Build base version with no GPU acceleration8pip install llama-cpp-python
9# With NVidia CUDA acceleration10CMAKE_ARGS="-DLLAMA_CUDA=on" pip install llama-cpp-python
11# Or with OpenBLAS acceleration12CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
13# Or with CLBLast acceleration14CMAKE_ARGS="-DLLAMA_CLBLAST=on" pip install llama-cpp-python
15# Or with AMD ROCm GPU acceleration (Linux only)16CMAKE_ARGS="-DLLAMA_HIPBLAS=on" pip install llama-cpp-python
17# Or with Metal GPU acceleration for macOS systems only18CMAKE_ARGS="-DLLAMA_METAL=on" pip install llama-cpp-python
19# Or with Vulkan acceleration20CMAKE_ARGS="-DLLAMA_VULKAN=on" pip install llama-cpp-python
21# Or with Kompute acceleration22CMAKE_ARGS="-DLLAMA_KOMPUTE=on" pip install llama-cpp-python
23# Or with SYCL acceleration24CMAKE_ARGS="-DLLAMA_SYCL=on -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx" pip install llama-cpp-python
2526# In windows, to set the variables CMAKE_ARGS in PowerShell, follow this format; eg for NVidia CUDA:27$env:CMAKE_ARGS ="-DLLAMA_CUDA=on"28pip install llama-cpp-python
Simple llama-cpp-python example code
python
1from llama_cpp import Llama
2from llama_cpp.llama_grammar import LlamaGrammar
3import json
45# Chat Completion API67grammar = LlamaGrammar.from_json_schema(json.dumps({8"type":"array",9"items":{10"type":"object",11"required":["name","arguments"],12"properties":{13"name":{14"type":"string"15},16"arguments":{17"type":"object"18}19}20}21}))2223llm = Llama(model_path="./gorilla-openfunctions-v2.IQ3_M.gguf", n_gpu_layers=33, n_ctx=16384)24response = llm.create_chat_completion(25 temperature =0.0,26 repeat_penalty =1.1,27 messages =[28{29"role":"user",30"content":"What's the weather like in Oslo and Stockholm?"31}32],33 tools=[{34"type":"function",35"function":{36"name":"get_current_weather",37"description":"Get the current weather in a given location",38"parameters":{39"type":"object",40"properties":{41"location":{42"type":"string",43"description":"The city and state, e.g. San Francisco, CA"44},45"unit":{46"type":"string",47"enum":["celsius","fahrenheit"]48}49},50"required":["location"]51}52}53}],54 grammar = grammar
55)56print(json.loads(response["choices"][0]["text"]))5758print(llm.create_chat_completion(59 temperature =0.0,60 repeat_penalty =1.1,61 messages =[62{63"role":"user",64"content":"What's the weather like in Oslo and Stockholm?"65},66{# The tool_calls is from the response to the above with tool_choice active67"role":"assistant",68"content":None,69"tool_calls":[70{71"id":"call__0_get_current_weather_cmpl-...",72"type":"function",73"function":{74"name":"get_current_weather",75"arguments":'{ "location": "Oslo, NO" ,"unit": "celsius"} '76}77}78]79},80{# The tool_call_id is from tool_calls and content is the result from the function call you made81"role":"tool",82"content":"20",83"tool_call_id":"call__0_get_current_weather_cmpl-..."84}85],86 tools=[{87"type":"function",88"function":{89"name":"get_current_weather",90"description":"Get the current weather in a given location",91"parameters":{92"type":"object",93"properties":{94"location":{95"type":"string",96"description":"The city and state, e.g. San Francisco, CA"97},98"unit":{99"type":"string",100"enum":["celsius","fahrenheit"]101}102},103"required":["location"]104}105}106}],107#tool_choice={108# "type": "function",109# "function": {110# "name": "get_current_weather"111# }112#}113))
Gorilla OpenFunctions extends Large Language Model(LLM) Chat Completion feature to formulate
executable APIs call given natural language instructions and API context. With OpenFunctions v2,
we now support:
Multiple functions - choose betwen functions
Parallel functions - call the same function N time with different parameter values
Multiple & parallel - both of the above in a single chatcompletion call (one generation)
Relevance detection - when chatting, chat. When asked for function, returns a function
Python - supports string, number, boolean, list, tuple, dict parameter datatypes and Any for those not natively supported.
JAVA - support for byte, short, int, float, double, long, boolean, char, Array, ArrayList, Set, HashMap, Hashtable, Queue, Stack, and Any datatypes.
JavaScript - support for String, Number, Bigint, Boolean, dict (object), Array, Date, and Any datatypes.
Gorilla Openfunctions v2 is a 7B parameter model, and is built on top of the deepseek coder LLM. Check out openfunctions-v2 blog to learn more about the data composition and some insights into the training process.
Example Usage (Hosted)
OpenFunctions is compatible with OpenAI Functions
!pip install openai==0.28.1
Point to Gorilla hosted servers
python
1import openai
23defget_gorilla_response(prompt="Call me an Uber ride type \"Plus\" in Berkeley at zipcode 94704 in 10 minutes", model="gorilla-openfunctions-v0", functions=[]):4 openai.api_key ="EMPTY"5 openai.api_base ="http://luigi.millennium.berkeley.edu:8000/v1"6try:7 completion = openai.ChatCompletion.create(8 model="gorilla-openfunctions-v2",9 temperature=0.0,10 messages=[{"role":"user","content": prompt}],11 functions=functions,12)13return completion.choices[0]14except Exception as e:15print(e, model, prompt)
Pass the user argument and set of functions, Gorilla OpenFunctions returns a fully formatted json
python
1query ="What's the weather like in the two cities of Boston and San Francisco?"2functions =[3{4"name":"get_current_weather",5"description":"Get the current weather in a given location",6"parameters":{7"type":"object",8"properties":{9"location":{10"type":"string",11"description":"The city and state, e.g. San Francisco, CA",12},13"unit":{"type":"string","enum":["celsius","fahrenheit"]},14},15"required":["location"],16},17}18]19get_gorilla_response(query, functions=functions)
Expected output NEW
Gorilla returns a readily accessible string AND Open-AI compatible JSON.
We have retained the string functionality that our community loved from OpenFunctions v1 get_current_weather(location='Boston, MA'), get_current_weather(location='San Francisco, CA') above. And Notice the function_call key in the JSON to be OpenAI compatible.
This is possible in OpenFunctions v2, because we ensure that the output includes the name of the argument and not just the value. This enables us to parse the output into a JSON. In those scenarios where the output is not parsable into JSON, we will always return the function call string.
End to End Example
Run the example code in [ofv2_hosted.py](https://github.com/ShishirPatil/gorilla/tree/main/openfunctions) to see how the model works.
If you want to Run OpenFunctions locally, here is the prompt format that we used:
python
1defget_prompt(user_query:str, functions:list=[])->str:2"""
3 Generates a conversation prompt based on the user's query and a list of functions.
45 Parameters:
6 - user_query (str): The user's query.
7 - functions (list): A list of functions to include in the prompt.
89 Returns:
10 - str: The formatted conversation prompt.
11 """12 system ="You are an AI programming assistant, utilizing the Gorilla LLM model, developed by Gorilla LLM, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer."13iflen(functions)==0:14returnf"{system}\n### Instruction: <<question>> {user_query}\n### Response: "15 functions_string = json.dumps(functions)16returnf"{system}\n### Instruction: <<function>>{functions_string}\n<<question>>{user_query}\### Response: "
And you can use the following code to format the response:
python
12from openfunctions_utils import strip_function_calls, parse_function_call
34defformat_response(response:str):5"""
6 Formats the response from the OpenFunctions model.
78 Parameters:
9 - response (str): The response generated by the LLM.
1011 Returns:
12 - str: The formatted response.
13 - dict: The function call(s) extracted from the response.
1415 """16 function_call_dicts =None17try:18 response = strip_function_calls(response)19# Parallel function calls returned as a str, list[dict]20iflen(response)>1:21 function_call_dicts =[]22for function_call in response:23 function_call_dicts.append(parse_function_call(function_call))24 response =", ".join(response)25# Single function call returned as a str, dict26else:27 function_call_dicts = parse_function_call(response[0])28 response = response[0]29except Exception as e:30# Just faithfully return the generated response str to the user31pass32return response, function_call_dicts
33
Note: Use the get_prompt and format_response only if you are hosting it Locally. If you are using the Berkeley hosted models through the Chat-completion API, we do this in the backend, so you don't have to do this. The model is supported in Hugging Face 🤗 Transformers and can be run up locally:
License
Gorilla OpenFunctions v2 is distributed under the Apache 2.0 license. This software incorporates elements from the Deepseek model. Consequently, the licensing of Gorilla OpenFunctions v2 adheres to the Apache 2.0 license, with additional terms as outlined in Appendix A of the Deepseek license.
Contributing
Gorilla is an open source effort from UC Berkeley and we welcome contributors.
Please email us your comments, criticism, and questions. More information about the project can be found at https://gorilla.cs.berkeley.edu/