Search

Search papers and lessons

ToolLLM: Facilitating Large Language Models to Master 16000+ Real-world APIs

Yujia Qin, Shihao Liang, Yining Ye et al. · 2023

ToolLLM builds a large instruction dataset of real API calls, labelled by a search over solution paths, and trains LLaMA on it so the model can use unseen APIs about as well as ChatGPT.

On this page

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

TL;DR

Open-source language models were weak at using tools: calling outside APIs with the right arguments and chaining several calls. ToolLLM tackles this in three parts. It builds ToolBench, an instruction-tuning dataset of about 200,000 instructions over 16,464 real REST APIs, where each instruction comes with a labelled solution path. It labels those paths with a new depth-first search over possible API calls. It then fine-tunes LLaMA on the data and reports that the result, ToolLLaMA, handles unseen instructions and APIs at about the level of ChatGPT on the authors' evaluation.

Builds on: Instruction Tuning, ReAct Prompting, Tree Search, Tool Use · Leads to: LLM Agent

Why it mattered

Tool use is what turns a chat model into something that can act: look up live data, book, query a database, or compose several services. Before this paper, the strongest tool users were closed models such as ChatGPT and GPT-4, and the open models that people could run themselves were far behind. The paper gives a public recipe for closing that gap, and a dataset and evaluator that others could reuse.

Its practical lessons are visible in later agent work. The API retriever is a standard pattern: when a catalogue is too large to fit in a prompt, a retriever picks the few APIs to show the model. Searching over solution paths, rather than following one chain of thought, is an idea that later agent-training work has explored. ToolEval, an automatic judge built on LLM judging, was an early example of evaluating agents by pass rate and by pairwise comparison, not by exact-match answers.

The problem

Three things made tool use hard. First, the instruction tuning that open models had received focused on language tasks and seldom included calls to outside APIs, so the models had little practice with the format. Second, real APIs are messy: many return errors, change over time, and are poorly documented, so a plan that looks right may fail. Third, a useful task often needs several calls in sequence, where an early mistake can send the model into a loop, such as calling the same endpoint with the wrong parameters over and over.

Two existing approaches fell short. Chain-of-thought and ReAct Prompting explore one path at a time, so one wrong step can trap them. And training data made by hand is expensive for thousands of APIs. The paper's question is whether a model can generate its own training data from real API documentation, using search to find solutions that work.

How it works

Here is the pipeline, traced through one small case. The stages run in order.

  1. Collect the APIs. The authors crawl RapidAPI Hub, which groups APIs into 49 categories and about 500 finer collections. They gather 10,853 tools with 53,190 APIs, then filter out those that return persistent errors or are poorly maintained. The retained set is 3,451 tools with 16,464 APIs. Check: each stage removes the unreliable APIs before any training data is made from them.
  2. Sample APIs and write instructions. Pick a few APIs, give their documentation and three seed examples written by humans to the teacher model, ChatGPT, and ask for instructions that need those APIs, along with the relevant APIs for each instruction. Single-tool instructions use one tool's APIs. Multi-tool instructions draw 2 to 5 tools from the same category or collection, since tools in one hub category are usually related. Check: the retained pairs are about 200,000, split into 87,413 single-tool, 84,815 intra-category multi-tool and 25,251 intra-collection multi-tool instructions.
  3. Search for a solution path. For each instruction, the teacher is asked to call APIs one at a time, reading each real response before the next call. Suppose the instruction needs the weather in a city, and the first endpoint returns a 404 error. A plain chain of thought would keep retrying that endpoint. The depth-first search instead records the failure, takes a "give up" action on that branch, and returns to the parent node to try a different API. It goes deeper along the first branch that works. Check: the failed branch is kept as a dead end, and the search moves on rather than looping.
  4. Keep the passing paths. A path counts as a valid training example if it ends with a final answer that completes the instruction within a budget of calls. Only these paths are kept. Check: the search cost is paid once, and the training set holds only answers that worked against real responses.
  5. Train ToolLLaMA. Fine-tune LLaMA-2 7B on the instruction and solution pairs. The original context window of 4,096 tokens is too short for long API responses, so the authors extend it to 8,192 with positional interpolation. Check: the model sees the full conversation, including responses, when it is trained.
  6. Add a retriever. Train a Sentence-BERT retriever on the instruction and relevant API pairs, so that for a new instruction the top few APIs can be fed to ToolLLaMA. Check: the model is no longer given the answer set of APIs, only a retrieved shortlist.
flowchart LR
  A[RapidAPI tools] --> B[Filter unreliable APIs]
  B --> C[Sample APIs and write instructions]
  C --> D[Depth-first search over API calls]
  D --> E[Keep passing solution paths]
  E --> F[Fine-tune LLaMA-2 7B]
  G[API retriever] --> F

The math

The paper states a few quantities precisely. The first is the retriever's score. Given an instruction qq and an API document dd, the encoders produce embeddings eq\mathbf{e}_q and ed\mathbf{e}_d, and relevance is their similarity,

s(q,d)=eq⊤ed,s(q, d) = \mathbf{e}_q^\top \mathbf{e}_d,

with training that pushes relevant APIs above sampled negatives, the usual Contrastive Learning objective. Retrieval is scored with NDCG at 1 and 5, a rank measure that gives more credit to relevant items near the top:

DCG@k=∑i=1krelilog⁡2(i+1),NDCG@k=DCG@kIDCG@k,\mathrm{DCG}@k = \sum_{i=1}^{k} \frac{\mathrm{rel}_i}{\log_2(i + 1)}, \qquad \mathrm{NDCG}@k = \frac{\mathrm{DCG}@k}{\mathrm{IDCG}@k},

where reli\mathrm{rel}_i is the relevance of the item at rank ii and IDCG@k\mathrm{IDCG}@k is the best possible value for kk items, so the score lies between 0 and 1.

The second is the pass rate. For an evaluation set of instructions, it is the fraction of instructions for which the model reaches a final answer within the call budget. The third is the win rate. Given two methods, it is the fraction of head-to-head comparisons that the method wins, as judged by ToolEval. The authors report that ToolEval agrees with human annotators on 87.1 percent of pass-rate judgements and 80.3 percent of win-rate judgements.

Worked examples

Example
Example 1: reading an NDCG score (tiny)

Setup: a retriever returns three APIs for one instruction, and only the first is relevant. Compute NDCG at 3.

  1. The relevance vector is (1,0,0)(1, 0, 0).
  2. DCG at 3 is 1/log⁡22+0+0=11/\log_2 2 + 0 + 0 = 1.
  3. The ideal ordering is the same, so IDCG at 3 is also 1.
  4. NDCG at 3 is 1/1=11 / 1 = 1.

Interpretation: a perfect ranking scores 1. If the relevant API were in position 2 instead, the DCG would be 1/log⁡23≈0.631/\log_2 3 \approx 0.63, so the same retrieval scores lower.

Example
Example 2: pass rate and win rate (standard)

Setup: a model is tested on 10 instructions and passes 7. Against a baseline, it wins 6 of 10 head-to-head comparisons.

  1. Pass rate is 7 / 10 = 0.70, or 70 percent.
  2. Win rate is 6 / 10 = 0.60, or 60 percent.
  3. A win rate above 50 percent means the model beats the baseline in more comparisons than it loses.

Interpretation: pass rate asks whether the task was completed at all, and win rate asks whether the answer was better than the reference. A model can have a high pass rate and a modest win rate if its answers are complete but not preferred.

Example
Example 3: how much the search adds (realistic)

Setup: suppose that on a hard set of multi-tool instructions, a single run passes 20 percent of instructions, and a search that allows five retries per instruction passes 60 percent. These numbers are illustrative, not the paper's. Compute the gain and say what it means for annotation cost.

  1. The absolute gain is 60 − 20 = 40 percentage points.
  2. The relative gain is 40 / 20 = 2, so the search passes twice as many instructions.
  3. If each instruction costs the same number of model calls, the search spends about five times as many calls per instruction, so the cost per passing example is 5/0.6≈8.35 / 0.6 \approx 8.3 calls, compared with 1/0.2=51 / 0.2 = 5 for the single run.

Interpretation: in this illustration the search costs more per passing example, about 8.3 calls against 5. Its value is not cheaper success on easy instructions. It is that it solves instructions a single run cannot solve at any budget, which is the kind of gain the authors report for depth-first search against plain ReAct.

Try it: a single run passes 30 percent of instructions, and the search passes 45 percent with the same cost per attempt. Which costs less per passing example, and by how much? Answer: the single run costs 1/0.30≈3.31/0.30 \approx 3.3 attempts per pass and the search costs 1/0.45≈2.21/0.45 \approx 2.2, so the search needs about one third fewer attempts per passing example.

Results

Main comparison. Across the test instructions, ChatGPT and GPT-4 both pass more instructions when they use the depth-first search than when they use plain ReAct. The authors read this as evidence that the search is a large lever for the same model, not only a bigger model.

ToolLLaMA. With the search, ToolLLaMA comes close to ChatGPT with the same search on pass rate and win rate, which is the headline result. Retrieving a shortlist of APIs with the authors' retriever, instead of giving the model the ground-truth API set, costs little accuracy.

Unseen instructions, tools and categories. The test levels are unseen instructions, unseen tools in a seen category, and unseen tools in an unseen category. ToolLLaMA generalises across them, with the strongest results on the multi-tool sets.

Limits. The data and the judge both come from ChatGPT, so the training labels and the evaluation share a teacher's biases, and ToolEval is validated against people on agreement rates rather than on every case. RapidAPI endpoints change over time, so exact scores are hard to reproduce later. The base model is a 7B LLaMA-2 variant, and the paper does not show how the results scale. The search also makes many more API calls than a single run, which is its main cost.

Reading guide

Check yourself

QuestionRecall: what does the depth-first search do differently from plain ReAct when an API call returns an error?Show answer

Plain ReAct continues along one path, so an early error can trap the model in a faulty loop. The depth-first search records the failure as a dead end, takes a give-up action on that branch, and expands a different node. It explores more of the action space and avoids being stuck on one wrong call.

QuestionComputation: a retriever returns three APIs and the relevant ones are at positions 2 and 3, with relevance (0, 1, 1). What is NDCG at 3?Show answer

DCG at 3 is 0 divided by log base 2 of 2, plus 1 divided by log base 2 of 3, plus 1 divided by log base 2 of 4. That is 0 + 0.631 + 0.5 = 1.131. The ideal ordering is (1, 1, 0), with DCG 1 + 0.631 = 1.631. NDCG is 1.131 / 1.631, about 0.69.

QuestionWhy: why does the paper extend the context window of LLaMA-2 before fine-tuning, and what would go wrong without it?Show answer

API responses can be very long, and the training conversations include the full response at each step. With a 4,096-token window, many solution paths would be cut off before the final answer, so the model would learn from incomplete traces. Positional interpolation extends the window to 8,192 so the model can see the complete conversation.

QuestionApplied: a team wants an open model to call the 2,000 internal APIs of their company. They have documentation and a test log of which calls worked. Which parts of the ToolLLM recipe would you reuse, and what would you check first?Show answer

Reuse the retriever to shortlist APIs for each request, since 2,000 documents will not fit in a prompt, and the search over calls to produce training paths that actually pass. Check first that the internal APIs are reliable enough to label, because the filtering step exists for that reason, and that the evaluation judge is validated against your own reviewers rather than only against a public teacher model.

Sources

Read the full paper

Yujia Qin, Shihao Liang, Yining Ye et al., 2023. arXiv:2307.16789