File size: 23,180 Bytes
6ac4e9b
ac699f6
 
 
 
6ac4e9b
ac699f6
 
 
 
6ac4e9b
ac699f6
 
 
 
 
 
 
 
 
 
 
 
1f9fb61
 
ac699f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f9fb61
ac699f6
 
 
 
 
 
 
 
 
1f9fb61
ac699f6
 
 
 
 
 
 
 
 
 
1f9fb61
ac699f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a7102
ac699f6
 
 
 
 
 
 
 
 
 
 
 
 
36b22a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
639a998
 
36b22a6
 
 
639a998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7825e6f
639a998
7825e6f
 
36b22a6
 
 
639a998
36b22a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
639a998
 
 
 
 
7825e6f
 
639a998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5811092
639a998
 
 
 
36b22a6
 
639a998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b22a6
639a998
 
 
 
 
 
 
36b22a6
 
 
ac699f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
---
base_model: gorilla-llm/gorilla-openfunctions-v2
language:
- en
pipeline_tag: text-generation
license: apache-2.0
model_creator: Gorilla LLM (UC Berkely)
model_name: Gorilla OpenFunctions v2
model_type: deepseek
quantized_by: CISC
---

# Gorilla OpenFunctions v2  - SOTA GGUF
- Model creator: [Gorilla LLM](https://huggingface.co/gorilla-llm)
- Original model: [Gorilla OpenFunctions v2](https://huggingface.co/gorilla-llm/gorilla-openfunctions-v2)

<!-- description start -->
## Description

This repo contains State Of The Art quantized GGUF format model files for [Gorilla OpenFunctions v2](https://huggingface.co/gorilla-llm/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](https://github.com/ShishirPatil/gorilla/raw/main/openfunctions/openfunctions-v1/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](https://github.com/ggerganov/llama.cpp/commit/f4ab2a41476600a98067a9474ea8f9e6db41bcfa) 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!

<!-- description end -->


<!-- prompt-template start -->
## 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: 

```

<!-- prompt-template end -->


<!-- compatibility_gguf start -->
## Compatibility

These quantised GGUFv3 files are compatible with llama.cpp from February 27th 2024 onwards, as of commit [0becb22](https://github.com/ggerganov/llama.cpp/commit/0becb22ac05b6542bd9d5f2235691aa1d3d4d307)

They are also compatible with many third party UIs and libraries provided they are built using a recent llama.cpp.

## Explanation of quantisation methods

<details>
  <summary>Click to see details</summary>

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.
</details>
<!-- compatibility_gguf end -->

<!-- README_GGUF.md-provided-files start -->
## Provided files

| Name | Quant method | Bits | Size | Max RAM required | Use case |
| ---- | ---- | ---- | ---- | ---- | ----- |
| [gorilla-openfunctions-v2.IQ1_S.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ1_S.gguf) | IQ1_S | 1 | 1.5 GB| 3.5 GB | smallest, significant quality loss - **TBD**: Waiting for [this issue](https://github.com/ggerganov/llama.cpp/issues/5996) to be resolved |
| [gorilla-openfunctions-v2.IQ2_XXS.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ2_XXS.gguf) | IQ2_XXS | 2 | 1.8 GB| 3.8 GB | very small, high quality loss |
| [gorilla-openfunctions-v2.IQ2_XS.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ2_XS.gguf) | IQ2_XS | 2 | 1.9 GB| 3.9 GB | very small, high quality loss |
| [gorilla-openfunctions-v2.IQ2_S.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ2_S.gguf) | IQ2_S | 2 | 2.1 GB| 4.1 GB | small, substantial quality loss |
| [gorilla-openfunctions-v2.IQ2_M.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ2_M.gguf) | IQ2_M | 2 | 2.2 GB| 4.2 GB | small, greater quality loss |
| [gorilla-openfunctions-v2.IQ3_XXS.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ3_XXS.gguf) | IQ3_XXS | 3 | 2.5 GB| 4.5 GB | very small, high quality loss |
| [gorilla-openfunctions-v2.IQ3_XS.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ3_XS.gguf) | IQ3_XS | 3 | 2.7 GB| 4.7 GB | small, substantial quality loss |
| [gorilla-openfunctions-v2.IQ3_S.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ3_S.gguf) | IQ3_S | 3 | 2.8 GB| 4.8 GB | small, greater quality loss |
| [gorilla-openfunctions-v2.IQ3_M.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ3_M.gguf) | IQ3_M | 3 | 3.0 GB| 5.0 GB | medium, balanced quality - recommended |
| [gorilla-openfunctions-v2.IQ4_XS.gguf](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.IQ4_XS.gguf) | IQ4_XS | 4 | 3.4 GB| 5.4 GB | small, substantial quality loss |

Generated importance matrix file: [gorilla-openfunctions-v2.imatrix.dat](https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF/blob/main/gorilla-openfunctions-v2.imatrix.dat)

**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.

<!-- README_GGUF.md-provided-files end -->

<!-- README_GGUF.md-how-to-run start -->
## Example `llama.cpp` command

Make sure you are using `llama.cpp` from commit [0becb22](https://github.com/ggerganov/llama.cpp/commit/0becb22ac05b6542bd9d5f2235691aa1d3d4d307) or later.

```shell
./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](https://github.com/ggerganov/llama.cpp/issues/4425).

For other parameters and how to use them, please refer to [the llama.cpp documentation](https://github.com/ggerganov/llama.cpp/blob/master/examples/main/README.md)

## How to run from Python code

You can use GGUF models from Python using the [llama-cpp-python](https://github.com/abetlen/llama-cpp-python) module.

### How to load this model in Python code, using llama-cpp-python

For full documentation, please see: [llama-cpp-python docs](https://llama-cpp-python.readthedocs.io/en/latest/).

#### First install the package

Run one of the following commands, according to your system:

```shell
# Prebuilt wheel with basic CPU support
pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
# Prebuilt wheel with NVidia CUDA acceleration
pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121 (or cu122 etc.)
# Prebuilt wheel with Metal GPU acceleration
pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/metal
# Build base version with no GPU acceleration
pip install llama-cpp-python
# With NVidia CUDA acceleration
CMAKE_ARGS="-DLLAMA_CUDA=on" pip install llama-cpp-python
# Or with OpenBLAS acceleration
CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
# Or with CLBLast acceleration
CMAKE_ARGS="-DLLAMA_CLBLAST=on" pip install llama-cpp-python
# Or with AMD ROCm GPU acceleration (Linux only)
CMAKE_ARGS="-DLLAMA_HIPBLAS=on" pip install llama-cpp-python
# Or with Metal GPU acceleration for macOS systems only
CMAKE_ARGS="-DLLAMA_METAL=on" pip install llama-cpp-python
# Or with Vulkan acceleration
CMAKE_ARGS="-DLLAMA_VULKAN=on" pip install llama-cpp-python
# Or with Kompute acceleration
CMAKE_ARGS="-DLLAMA_KOMPUTE=on" pip install llama-cpp-python
# Or with SYCL acceleration
CMAKE_ARGS="-DLLAMA_SYCL=on -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx" pip install llama-cpp-python

# In windows, to set the variables CMAKE_ARGS in PowerShell, follow this format; eg for NVidia CUDA:
$env:CMAKE_ARGS = "-DLLAMA_CUDA=on"
pip install llama-cpp-python
```

#### Simple llama-cpp-python example code

```python
from llama_cpp import Llama
from llama_cpp.llama_grammar import LlamaGrammar
import json

# Chat Completion API

grammar = LlamaGrammar.from_json_schema(json.dumps({
    "type": "array",
    "items": {
        "type": "object",
        "required": [ "name", "arguments" ],
        "properties": {
            "name": {
                "type": "string"
            },
            "arguments": {
                "type": "object"
            }
        }
    }
}))

llm = Llama(model_path="./gorilla-openfunctions-v2.IQ3_M.gguf", n_gpu_layers=33, n_ctx=16384)
response = llm.create_chat_completion(
      temperature = 0.0,
      repeat_penalty = 1.1,
      messages = [
        {
          "role": "user",
          "content": "What's the weather like in Oslo and Stockholm?"
        }
      ],
      tools=[{
        "type": "function",
        "function": {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": [ "celsius", "fahrenheit" ]
              }
            },
            "required": [ "location" ]
          }
        }
      }],
      grammar = grammar
)
print(json.loads(response["choices"][0]["text"]))

print(llm.create_chat_completion(
      temperature = 0.0,
      repeat_penalty = 1.1,
      messages = [
        {
          "role": "user",
          "content": "What's the weather like in Oslo and Stockholm?"
        },
        { # The tool_calls is from the response to the above with tool_choice active
          "role": "assistant",
          "content": None,
          "tool_calls": [
            {
              "id": "call__0_get_current_weather_cmpl-...",
              "type": "function",
              "function": {
                "name": "get_current_weather",
                "arguments": '{ "location": "Oslo, NO" ,"unit": "celsius"} '
              }
            }
          ]
        },
        { # The tool_call_id is from tool_calls and content is the result from the function call you made
          "role": "tool",
          "content": "20",
          "tool_call_id": "call__0_get_current_weather_cmpl-..."
        }
      ],
      tools=[{
        "type": "function",
        "function": {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": [ "celsius", "fahrenheit" ]
              }
            },
            "required": [ "location" ]
          }
        }
      }],
      #tool_choice={
      #  "type": "function",
      #  "function": {
      #    "name": "get_current_weather"
      #  }
      #}
))
```

<!-- README_GGUF.md-how-to-run end -->

<!-- original-model-card start -->
# Original model card: Gorilla OpenFunctions v2 

💡 SoTA for open-source models. On-par with GPT-4. 

🚀 Check out the [Berkeley Function Calling Leaderboard](https://gorilla.cs.berkeley.edu/leaderboard)   
📣 Read more in our [OpenFunctions v2 release blog](https://gorilla.cs.berkeley.edu/blogs/7_open_functions_v2.html)

## Introduction
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:
1. Multiple functions - choose betwen functions 
2. Parallel functions - call the same function `N` time with different parameter values
3. Multiple & parallel - both of the above in a single chatcompletion call (one generation)
4. Relevance detection - when chatting, chat. When asked for function, returns a function
5. Python - supports `string, number, boolean, list, tuple, dict` parameter datatypes and `Any` for those not natively supported. 
6. JAVA - support for `byte, short, int, float, double, long, boolean, char, Array, ArrayList, Set, HashMap, Hashtable, Queue, Stack, and Any` datatypes.
7. JavaScript - support for `String, Number, Bigint, Boolean, dict (object), Array, Date, and Any` datatypes.
8. REST - native REST support


## Performance

| Model | Accuracy | 
|---|---|
|GPT-4-0125-Preview | 83.80% |
|Gorilla-openfunctions-v2 | 83.55% |
|GPT-3.5-turbo | 81.63% |
|Mistral-medium | 79.56% |
|Nexusflow Raven-v2 | 54.46% |
|GPT-4-0613 | 53.49% |


## Models Available
|Model | Functionality|
|---|---|
|gorilla-openfunctions-v2 | Multiple, parallel, multiple & parallel, relevance detection, Python + JAVA + JS + REST|
|gorilla-openfunctions-v1 | Parallel functions, and can choose between functions|
|gorilla-openfunctions-v0 | Given a function, and user intent, returns properly formatted json with the right arguments|

All of our models are hosted on our Huggingface UC Berkeley gorilla-llm org: [gorilla-openfunctions-v2](https://huggingface.co/gorilla-llm/gorilla-openfunctions-v2), [gorilla-openfunctions-v1](https://huggingface.co/gorilla-llm/gorilla-openfunctions-v1), and [gorilla-openfunctions-v0](https://huggingface.co/gorilla-llm/gorilla-openfunctions-v0).

## Training

Gorilla Openfunctions v2 is a 7B parameter model, and is built on top of the [deepseek coder](https://huggingface.co/deepseek-ai/deepseek-coder-7b-instruct-v1.5) LLM. Check out [openfunctions-v2 blog](https://gorilla.cs.berkeley.edu/blogs/7_open_functions_v2.html) to learn more about the data composition and some insights into the training process. 



## Example Usage (Hosted)

1. OpenFunctions is compatible with OpenAI Functions

```bash
!pip install openai==0.28.1
```

2. Point to Gorilla hosted servers

```python
import openai

def get_gorilla_response(prompt="Call me an Uber ride type \"Plus\" in Berkeley at zipcode 94704 in 10 minutes", model="gorilla-openfunctions-v0", functions=[]):
  openai.api_key = "EMPTY"
  openai.api_base = "http://luigi.millennium.berkeley.edu:8000/v1"
  try:
    completion = openai.ChatCompletion.create(
      model="gorilla-openfunctions-v2",
      temperature=0.0,
      messages=[{"role": "user", "content": prompt}],
      functions=functions,
    )
    return completion.choices[0]
  except Exception as e:
    print(e, model, prompt)
```

3. Pass the user argument and set of functions, Gorilla OpenFunctions returns a fully formatted json

```python
query = "What's the weather like in the two cities of Boston and San Francisco?"
functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA",
                },
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
    }
]
get_gorilla_response(query, functions=functions)
```

4. Expected output **NEW**

Gorilla returns a readily accessible string **AND** Open-AI compatible JSON. 

```python
{
  "index": 0,
  "message": {
    "role": "assistant",
    "content": "get_current_weather(location='Boston, MA'), get_current_weather(location='San Francisco, CA')",
    "function_call": [
      {
        "name": "get_current_weather",
        "arguments": {
          "location": "Boston, MA"
        }
      },
      {
        "name": "get_current_weather",
        "arguments": {
          "location": "San Francisco, CA"
        }
      }
    ]
  },
  "finish_reason": "stop"
}

```

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.

```bash
python ofv2_hosted.py
```

Expected Output:

```bash
(.py3) shishir@dhcp-132-64:~/Work/Gorilla/openfunctions/$ python ofv2_hosted.py
--------------------
Function call strings(s): get_current_weather(location='Boston, MA'), get_current_weather(location='San Francisco, CA')
--------------------
OpenAI compatible `function_call`: [<OpenAIObject at 0x1139ba890> JSON: 
{
  "name": "get_current_weather",
  "arguments": 
  {
    "location": "Boston, MA"
  }
}, <OpenAIObject at 0x1139ba930> JSON: {
  "name": "get_current_weather",
  "arguments": 
  {
    "location": "San Francisco, CA"
  }
}]
```


## Running OpenFunctions Locally

If you want to Run OpenFunctions locally, here is the prompt format that we used: 

```python
def get_prompt(user_query: str, functions: list = []) -> str:
    """
    Generates a conversation prompt based on the user's query and a list of functions.

    Parameters:
    - user_query (str): The user's query.
    - functions (list): A list of functions to include in the prompt.

    Returns:
    - str: The formatted conversation prompt.
    """
    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."
    if len(functions) == 0:
        return f"{system}\n### Instruction: <<question>> {user_query}\n### Response: "
    functions_string = json.dumps(functions)
    return f"{system}\n### Instruction: <<function>>{functions_string}\n<<question>>{user_query}\### Response: "
```

Further, here is how we format the response:

Install the dependencies with:

```bash
pip3 install tree_sitter
git clone https://github.com/tree-sitter/tree-sitter-java.git
git clone https://github.com/tree-sitter/tree-sitter-javascript.git
```

And you can use the following code to format the response:

```python

from openfunctions_utils import strip_function_calls, parse_function_call

def format_response(response: str):
    """
    Formats the response from the OpenFunctions model.

    Parameters:
    - response (str): The response generated by the LLM.

    Returns:
    - str: The formatted response.
    - dict: The function call(s) extracted from the response.

    """
    function_call_dicts = None
    try:
        response = strip_function_calls(response)
        # Parallel function calls returned as a str, list[dict]
        if len(response) > 1: 
            function_call_dicts = []
            for function_call in response:
                function_call_dicts.append(parse_function_call(function_call))
            response = ", ".join(response)
        # Single function call returned as a str, dict
        else:
            function_call_dicts = parse_function_call(response[0])
            response = response[0]
    except Exception as e:
        # Just faithfully return the generated response str to the user
        pass
    return response, function_call_dicts
        
```

**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](https://github.com/deepseek-ai/DeepSeek-LLM/blob/6712a86bfb7dd25c73383c5ad2eb7a8db540258b/LICENSE-MODEL) 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/](https://gorilla.cs.berkeley.edu/)

<!-- original-model-card end -->