Search

Search papers and lessons

Gorilla: Large Language Model Connected with Massive APIs

Shishir G. Patil, Tianjun Zhang, Xin Wang et al. · 2023

Gorilla fine-tunes a 7B LLaMA model to write machine-learning API calls with retrieved documentation in its prompt, beating GPT-4 on its benchmark and adapting when the docs change.

On this page

  • Colour = topic mix
  • Probability
  • Language & LLMs
  • Discrete math
  • Neural network basics
  • Calculus
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

Language models often invent function calls. Ask GPT-4 for a model that classifies images and it may name a model that does not exist, or a real library with the wrong arguments. Gorilla is a LLaMA-7B model fine-tuned on 1,645 machine-learning API calls, each paired with synthetic user requests, and it can read current API documentation placed in its prompt. The paper reports that Gorilla writes correct API calls more often than GPT-4 on its benchmark, hallucinates less, and keeps working when the documentation changes without retraining.

Builds on: Tool Use, Retrieval-Augmented Generation, Self-Instruct, Abstract Syntax Tree · Leads to: tool-calling models trained against a registry of real APIs, and retrieval setups where the documentation, not the weights, carries the latest facts

Why it mattered

The paper's introduction notes that leading LLM providers had started to offer plugins that let models call external tools through APIs. The paper's point is that a short list of tools in the prompt does not scale: a real API catalogue can hold thousands of overlapping entries, and a prompt cannot hold them all.

Three results from the paper stand out. First, a fine-tuned small model can beat a much larger general model on one narrow, checkable task. Second, the way you judge an answer matters: the authors compare the structure of a call with a reference rather than running it. Third, putting documentation into the prompt at answer time lets a model follow changes that happened after its training.

The idea of a model making its own training data comes from Self-Instruct, which showed that a model can generate its own instructions from a few seed examples, and Gorilla borrows that pattern for its data. The paper cites Toolformer, which taught a model to insert tool calls into its own text, as a recent example of this line of work.

The problem

Three problems stand in the way, and the paper names each one.

The first is scale. The introduction argues that tool use could make language models the main interface to computing and the web, but only if they can pick from a very large and changing set of APIs. Describing every API in one context window is not possible, and many APIs overlap in function with small differences in limits and arguments. The authors also note that prior tool work usually covered a small, well-documented set of APIs that could be injected into the prompt.

The second is accuracy of the call itself. A call has a function name and arguments. The model must get the name right (pick the correct model from a hub), the arguments right (the repository name and the model name), and must respect constraints the user states, such as a parameter budget or an accuracy floor. The paper's own example is a request for "an image classification model that uses less than 10M parameters, but maintains an ImageNet accuracy of at least 70%". Answering it needs reasoning about numbers stored in documentation, not just recognising a task.

The third is hallucination and staleness. The authors define a hallucination as a call that matches no API in their database at all: an entirely imagined tool. A wrong choice among real APIs is a different kind of error. Documentation also changes faster than a model can be retrained, so a model that memorised an old registry becomes wrong over time.

How it works

Here is the whole pipeline for one API record, from start to finish.

  1. Start with a record. Take one entry from a model hub, for example a PyTorch Hub model. Its model card is turned into a JSON object with fields such as domain, framework, functionality, API name, API call, arguments, environment requirements, example code, performance and description. Call this record D.
  2. Write the questions. Give GPT-4 the record D and three of six hand-written example pairs of (instruction, API) for that hub. Ask it for real-world requests that need this API, and tell it not to name the API or hint at it. Each record ends up with ten (instruction, API) pairs. The paper says the only human-written data are these 18 example pairs, six per hub. Check: ten pairs for one record.
  3. Turn each pair into a chat. Each (instruction, API) pair becomes one round of conversation: the user asks, the agent answers with the API call. Check: ten pairs give ten conversations, each with one user turn and one agent turn.
  4. Add the document when training with retrieval. For the retriever-aware version, the record D is appended to the user turn after the sentence "Use this API documentation for reference:". Now the question carries its own source, so the model learns to read the document in order to answer.
  5. Fine-tune. Run ordinary instruction fine-tuning on the base LLaMA-7B model with these conversations. The model is trained to produce the agent's turn given the user's turn.
  6. Answer a new request. At inference the user types a request. In zero-shot mode the request goes straight to Gorilla. In retrieval mode a retriever (BM25 or a GPT-based index) finds the most relevant API document in the database, and that document is appended to the request with the same sentence. Gorilla then writes the call. The paper adds no further prompt tuning.
  7. Check the answer. Parse the output into a syntax tree, and look for a matching subtree in the dataset. If the call matches the right API on the argument fields the authors chose to compare, it is correct. If it matches some other API in the database, it is a wrong choice. If it matches nothing, it is a hallucination.

The key design choice is step 4 combined with step 6. The model is not handed the answer; it is taught to read the documentation it is given and to answer from it. So when the documentation changes, the model's behaviour can change with it, with no new training.

flowchart LR
  A[API model card] --> B[JSON record]
  B --> C[GPT-4 writes 10 instructions per record]
  C --> D[Chat pairs: user asks, agent answers]
  B --> E[Documentation appended to the user turn]
  D --> F[Fine-tune LLaMA-7B = Gorilla]
  E --> F
  G[User request] --> H[Retriever returns top document]
  H --> F
  F --> I[API call]
  I --> J[Syntax-tree match: correct, wrong API, or hallucination]
Example
Tracing step 7 on a tiny case

Suppose the database holds the reference torch.hub.load(repo_or_dir="pytorch/vision", model="densenet121"). The compared fields are the function name, repo_or_dir and model. The optional argument pretrained=True is not compared.

  1. Candidate A: torch.hub.load(repo_or_dir="pytorch/vision", model="densenet121", pretrained=True). The function name, the repository and the model all match. The extra pretrained argument is not compared, so the reference tree is a subtree of the candidate. Correct.
  2. Candidate B: torch.hub.load(repo_or_dir="pytorch/vision", model="resnet50"). The name and repository match, but model differs. Suppose the database has a resnet50 entry under the same repository. Then B matches a different reference API, so it is a wrong choice. Error, not a hallucination.
  3. Candidate C: torch.hub.load(repo_or_dir="someuser/magic-net", model="oracle9"). No reference in the database has this repository or this model. Hallucination.

Interpretation: the test is strict about the compared fields and lenient about everything else, so a valid call with extra optional arguments still counts.

Example
Counting the training data for one hub

Take the Torch Hub set, which the paper reports as 95 records.

  1. Each hub has six hand-written seed examples. Sampling three of them gives (63)=20\binom{6}{3} = 20 distinct sets of seeds, so the same record can be paired with different example requests.
  2. Each record gets ten instruction pairs.
  3. For one record, 1×10=101 \times 10 = 10 pairs.
  4. For all 95 Torch Hub records, 95×10=95095 \times 10 = 950 pairs.
  5. Across all three hubs the paper reports 1,645 API records, so the full set is about 16,000 pairs (1,645×10=16,4501{,}645 \times 10 = 16{,}450).

Interpretation: the sampling step gives variety. Each record sees different example requests, so the synthetic questions do not all sound the same.

The math

The paper's math is light, but the definition of a correct answer carries the evaluation, so it is worth writing down.

The objects

A user request xx is a sentence. The model produces a call c^\hat{c}. The dataset holds a set of reference APIs A={a1,…,aM}\mathcal{A} = \{a_1, \dots, a_M\}. Each reference aja_j is a call with a fixed function name and a set of arguments that the authors chose to compare.

Step 4 in symbols: the training input

When the document dd for a request is added, the model sees the input [x;"Use this API documentation for reference:";d][x; \text{"Use this API documentation for reference:"}; d], where the semicolon means concatenation. The fine-tuning target is the agent's answer yy. Standard instruction fine-tuning minimises the usual next-token cross-entropy on yy:

L(θ)=−∑tlog⁡pθ(yt∣y<t,x,d)\mathcal{L}(\theta) = -\sum_{t} \log p_\theta(y_t \mid y_{\lt t}, x, d)

The sum runs over the tokens yty_t of the answer, θ\theta are the model weights, and pθp_\theta is the probability the model gives to the next token. The retrieval-free version drops dd from the condition.

Step 6 in symbols: retrieval

The retriever returns one document d⋆d^\star from the database D\mathcal{D} that scores highest for the request:

d⋆=arg⁡max⁡d∈Dscore⁡(x,d)d^\star = \arg\max_{d \in \mathcal{D}} \operatorname{score}(x, d)

Here score⁡\operatorname{score} is the retriever's similarity, for example BM25 over the document text. The argmax means "the document with the largest score". The paper uses top-1 retrieval, so one document is added.

Step 7 in symbols: the correctness test

Let T(⋅)T(\cdot) be the syntax tree of a call. A generated call c^\hat{c} is correct when the tree of some reference call aja_j is a subtree of T(c^)T(\hat{c}) on the compared fields:

correct(c^)=1[∃ aj∈A:T(aj) is a subtree of T(c^) on the compared fields]\text{correct}(\hat{c}) = \mathbf{1}\left[\exists\, a_j \in \mathcal{A} : T(a_j)\ \text{is a subtree of}\ T(\hat{c})\ \text{on the compared fields}\right]

Here 1[⋅]\mathbf{1}[\cdot] is 1 when the condition holds and 0 otherwise. The accuracy on a test set of NN requests is the mean of this indicator over the requests.

A hallucination uses a stronger condition: the call matches no reference in A\mathcal{A} at all. An error is a call that matches some reference API but fails on the compared fields, or matches the wrong API.

Results

The paper's main findings, with its own numbers. The percentages are the paper's stated differences.

Zero-shot accuracy. Gorilla gets the best zero-shot accuracy across the models the paper tests. The paper reports it as 20.43% better than GPT-4 and 10.75% better than ChatGPT, and as much as 83% better than LLaMA. The authors read this as evidence that, in their setting, fine-tuning on the API data beats retrieval alone.

Retrieval at test time. Gorilla trained without a retriever gains little from a ground-truth retriever at test time, and a poor retriever hurts it. The paper reports drops of 21.50% in Torch Hub and 47.57% in HuggingFace when BM25 or GPT-Index is used as the retriever.

Retrieval during training. Training with the ground-truth document helps. The paper reports gains of 12.37% in Torch Hub and 23.46% in HuggingFace over training without the document. But at test time the gap to ground truth is large: a GPT-Index retriever loses 29.20% accuracy and BM25 loses 52.27%.

Hallucination. Zero-shot prompting of GPT-4 and GPT-3.5 produces serious hallucinations, such as calling AutoModel.from_pretrained with arbitrary GitHub repository names. The paper also reports that GPT-3.5 has fewer hallucination errors than GPT-4 in the Torch Hub, HuggingFace and TensorFlow Hub settings, and suggests RLHF plays a central role in making models truthful.

Changes in documentation. The paper shows that a model trained with retrieved documents follows a change such as upgrading a backbone from ResNet-50 to ResNet-101. This is a qualitative result shown on examples, not a benchmark score.

Constraints. Section 4.3 tests whether models respect an accuracy constraint. For a query such as "at least 80% top-1 accuracy on ImageNet", the right model is ResNeXt-101 32x16d at 84.2%, not MobileNetV2 at 71.88%, even though both are classifiers hosted by Torch Hub.

Limits. The benchmark covers three ML hubs, and the paper says its HuggingFace set is not exhaustive. The paper does not execute the generated code, so it judges calls by structure, not by whether they run. It also notes that ambiguity is real: for image classification there are over 40 models that can be used, so several answers can be right.

Common misreadings. It is tempting to think that a call which looks right has picked the right API. The paper's point is that structure matching is the honest check when many answers are valid. It is also tempting to think that a retriever always helps. It does not: a non-optimal test-time retriever can misguide the model. The paper's conclusion is that with a good retriever, training with retrieval is the better method, and when no good retriever is available, zero-shot fine-tuning may be the preferred choice. Finally, a larger model is not automatically more truthful, as the GPT-3.5 and GPT-4 comparison shows.

Reading guide

Read the paper's sections in order, with the lessons each one needs.

  • Abstract and Section 1 (Introduction): the case for tool use at web scale. Needs Tool Use and the idea of Retrieval-Augmented Generation.
  • Section 2 (Related Work): the earlier tool and program-synthesis work. Needs In-Context Learning and Instruction Tuning for the terms it uses.
  • Section 3.1 (Dataset Collection) and 3.2 (Gorilla): the record format and the self-instruct data. Needs Self-Instruct and Fine-Tuning. The training format builds on LLaMA.
  • Section 3.2 (Gorilla, with retriever-aware training) and 3.3 (Verifying APIs): the retrieval step and the syntax-tree test. Needs BM25 and Abstract Syntax Tree.
  • Section 4 (Evaluation), 4.1 to 4.3: the accuracy tables, the test-time documentation change study, and the constraint study. Needs the results above and the retrieval lessons.
  • Section 6 (Limitations), and Appendix 8.2 (Gorilla Details): the scope of the benchmark, and the hyperparameters in Table 4 (learning rate 2e-5, batch size 64, five epochs, maximum sequence length 2048, trained on 8 A100 GPUs with 40 GB each).

Recap of the chain of ideas: tool use needs a catalogue, and a catalogue is too large for one prompt. Fine-tuning on synthetic (request, API) pairs teaches a model the catalogue's shape. Adding the document at training and at test time lets the model read changes. Syntax-tree matching separates wrong choices from invented tools.

What to read next: Toolformer, which teaches tool calls from the model's own text, and Sentence-BERT, which covers how a retriever can turn text into vectors for search.

Check yourself

QuestionRecall: what is the difference between a hallucination and an error in the paper's evaluation?Show answer
A hallucination is a call that matches no API in the database at all; it invents a tool. An error is a call that refers to a real API in the database but gets the choice or the compared arguments wrong.
QuestionComputation: a hub record has six seed examples and the sampling step takes three. How many distinct sets of three seeds can be chosen, and how many instruction pairs does one record get under the paper's ten-pair figure?Show answer
There are (63)=20\binom{6}{3} = 20 distinct sets of three seeds. One record gets ten instruction pairs.
QuestionWhy: the paper says a non-optimal retriever used at test time can misguide the model. Why does it still find that training with the right document helps?Show answer
Training with the ground-truth document gives the model a document to read while it learns the answer. The paper's ablation shows this helps by 12.37% on Torch Hub and 23.46% on HuggingFace, compared with training without a document. That gain only pays off when retrieval at test time is good, which the paper finds is not yet true for BM25 or GPT-Index.
QuestionApplied: a team has an internal API registry that changes weekly, and their retriever finds the right document about 60% of the time. Based on the paper's conclusion, what should they consider?Show answer
A retriever this weak is the case the paper flags: zero-shot fine-tuning may be preferred when no good retriever is available. The team should first try to improve the retriever, since retrieval-trained models gain from a good one. Then they should measure fine-tuning without retrieval against fine-tuning with retrieval on their own held-out requests. Retraining is the cost they must weigh, because the retrieval route is what lets the model follow weekly changes without retraining.

Sources

Read the full paper

Shishir G. Patil, Tianjun Zhang, Xin Wang et al., 2023. arXiv:2305.15334