A model that tries one path gets stuck at the first broken API. ToolLLM lets it back up and try another, and a 7B model learns to call 16,464 real APIs this way.
Press Run with ReACT, then pick DFSDT and run again. Watch what each one does when an API call returns an error. Then we build ToolLLM piece by piece: the 16,464 APIs, the instructions, the search, the training, the retriever and the judge.
You need a rough idea of what it means for one program to ask another program for data (Chapter 1 explains it) and a little Python. We build the rest from zero.
Based on ToolLLM: Facilitating Large Language Models to Master 16000+ Real-world APIs by Yujia Qin, Shihao Liang, Yining Ye, Kunlun Zhu, Lan Yan, Yaxi Lu, Yankai Lin, Xin Cong, Xiangru Tang, Bill Qian, Sihan Zhao, Lauren Hong, Runchu Tian, Ruobing Xie, Jie Zhou, Mark Gerstein, Dahai Li, Zhiyuan Liu and Maosong Sun (Tsinghua University and partners), arXiv 2307.16789. A reading for MIT MAS.S62 AI4AI, from Lecture 5.
Toy task, illustrative: a user wants a birthday surprise for a friend who likes an actress (the paper’s Figure 4 example). The tree, the API names and the 8-call budget are made up for the demo. The paper’s own numbers are the average pass rates in its Table 3, with ChatGPT: ReACT 35.3%, ReACT@N 44.5%, DFSDT 63.8%.
Chapter 0
See the gap between models that call real APIs and models that cannot, and meet the three parts of ToolLLM that close it
You type one sentence to an assistant: “We are planning a movie night in the mountains. Suggest a film, and tell me the weather up there.” A good answer needs facts that no model keeps in its weights. It needs to know what is streaming today and what the forecast says for tomorrow.
A person would open two apps. The assistant must do the same, and the apps it opens are called APIs.
An API (application programming interface) is a door that one program opens for another. You send a request through the door. The service sends back data. A tool is a bundle of such doors from one provider, for example a weather service with one door for today and one for the week. Tool use means that a language model picks a door, fills in its inputs, reads what comes back, and decides what to do next. Chapter 1 shows one door up close.
By 2023 the closed models, ChatGPT and GPT-4, could do this well. The open models, such as LLaMA and its chat-tuned cousins Vicuna and Alpaca, could talk but could not act. The paper measures that gap. Move the switch below and look at the zeros.
Each bar is the share of test instructions a model finished successfully (its pass rate). Choose how the model searches for a solution, and watch which bars move. Chapter 4 explains both methods.
Numbers are the paper’s Table 4, average column, pass rate in percent. Vicuna and Alpaca score 0.0 with both methods. Every model was given the correct APIs for each instruction (the paper calls this the oracle setting). ChatGPT, Claude-2, Text-Davinci-003 and GPT-4 are closed models.
Read the zeros twice. The authors tried hard prompt engineering, and Vicuna and Alpaca still passed no instruction at all. These models are not weak at tools. They have no tool skill to measure.
The reason is the data they were tuned on. Instruction tuning trains a model on pairs of an instruction and a good answer. The popular pairs teach chat, summaries and essays. Almost none of them show the odd skill that tool use needs: write a precise call, read a messy reply, then decide on the next call.
Before ToolLLM, several groups had built tool-use datasets. The paper finds three weaknesses in them.
First, the APIs were few or not real. Some datasets used a handful of APIs. Some never ran the call, so the model never saw a real reply, and real replies are often errors. Second, each task used one tool, and a person chose the right tool in advance. That cannot work when thousands of APIs exist. Third, the planning was weak. Earlier work used chain of thought or ReACT, which follow a single line of reasoning and have no way back from a mistake.
ToolLLM is a whole framework, in three parts. Each part answers one hole.
Notice the teacher and student. ChatGPT writes the tasks, solves them and grades them. A 7B open model learns from the result. In this course that is the interesting part: one AI builds the training data and the test for another AI. Lecture 5 asks what a harness (the code around a model that runs its loop and its tools) must provide. ToolLLM is a harness that makes training data.
The chapters follow the paper’s own order, with one extra chapter on the call itself.
Chapter 1
Open one API door by hand, then see how a model writes the request and how a program runs it
Open a movie site and type “batman” into the search box. Choose your country. Press Enter. A list appears. You did not see it, but your browser sent a short message to a computer far away, and that computer sent the list back.
That message exchange is the whole idea of a REST API. The word REST names a common style: the request is a web address, and the answer is plain text. Learn this one exchange and you know the building block of the paper.
A request has three parts. The method says what you want to do: GET means “give me data”. The path says which door, for example /v2/search/title. The parameters are the inputs, written after a question mark: ?title=batman&country=us.
The response has a status code and a body. Status 200 means success. Status 400 means “your request is wrong”, and 500 means “the server is broken”. The body is usually JSON, text built from named fields, such as {"title": "Batman"}.
Parameters come in two kinds. A required parameter must be present, or the call fails. An optional parameter has a default. Build a call below and break it on purpose.
This is a toy copy of the Search By Title API from the paper’s Figure 3. Pick the parameters. Leave a required one empty and see what happens.
Illustrative: the endpoint, the parameter names and the required/optional split follow the paper’s Figure 3 documentation of Streaming Availability. The titles, status codes and responses here are invented for the demo; no real server is called.
Two things matter for the model. A failed call still returns something, an error message, and the model must read it. And the request must match the documentation exactly. The model never touches the server. It only writes text.
For every API the authors keep a record: the tool name and description, the host address, and for each API its name, description, method, required parameters, optional parameters, a code snippet and an example response. This is the page a human developer would read.
The record is the model’s only manual. If it can read documentation, it can use an API it never saw in training. The paper tests exactly that in Chapter 8.
The authors use ChatGPT’s function call feature. Each API becomes a “function”, and its documentation goes into a field that lists the functions. The model answers in a fixed shape: Thought, then API Name, then Parameters. A thought is a short note the model writes to itself about what to do next.
The program around the model reads that text, runs the real request, and pastes the reply back as the next message. The paper adds two special functions. Finish with Final Answer carries the answer for the user. Finish by Giving Up says the task cannot be done from this state.
Step through one full exchange. It is the example from the paper’s Figure 4.
Each press adds one message. Colour shows who wrote it: the developer, the user, the model, or the program that ran the API.
The user request, the API name, the observation and the final answer follow the paper’s Figure 4. The system text is shortened from its appendix prompt, and the second thought is written for this demo.
Now the data flow in one line. At round t the model reads everything so far and writes one action.
Round 1: a1 ∼ LLM(Inst). Round 2: a2 ∼ LLM(Inst, a1, r1). Round 3: the same, with one more pair.
The history only grows. Each reply from an API lands in it, long or short, helpful or not. That is why Chapter 2 compresses replies and Chapter 5 needs a long context window. It is also why an early error can poison every later round, which Chapter 4 fixes.
Chapter 2
Gather thousands of live APIs from one marketplace, throw away the broken ones, and shorten the replies so they fit in a model’s head
Picture an app store with 53,000 apps. Many were abandoned years ago. Some crash when you open them. Some answer with a wall of text that no one can read. If you wanted to teach a student to use apps, you would not hand over the whole store. You would keep the ones that work.
That is the first phase of ToolBench, the dataset that the paper builds. The store is RapidAPI Hub, a marketplace where developers publish APIs and other developers call them. Anyone with a RapidAPI key can test and use them. The authors crawl it, test it, and keep the good part.
The hub has a hierarchy with four levels. A category is a coarse topic. There are 49 of them, such as sports, finance and weather. A collection is a finer group of more than 500, such as “Chinese APIs” or “database APIs”. A tool is one provider’s service. An API is one door inside a tool, for example “Search By Title” inside “Streaming Availability”.
For each tool the authors save its name, description and host address. For each API they save the name, description, HTTP method, required and optional parameters, request body, a runnable code snippet and an example response. Chapter 1 showed why that record matters: it is the manual.
The hierarchy also matters for a later step. Tools in the same category tend to belong together, so Chapter 3 uses the category to build tasks that combine tools in a natural way.
The first crawl returned 10,853 tools and 53,190 APIs. Many did not work. Some returned 404 errors, and some returned internal server errors. A training example built on a dead API teaches the model nothing.
The filter has two tests. The first is an initial test: call the API in a basic way and discard it if it does not run. The second is an example response check. The authors make a call, then judge the response time and quality. They drop APIs that are consistently slow. They drop APIs that return HTML source code or an error page where data should be.
What survives is 3,451 tools and 16,464 APIs. Slide the filter and watch the funnel.
Top bar: tools. Bottom bar: APIs. Drag the slider from the raw crawl to the filtered set.
The two end points are the paper’s (Section 2.1): 10,853 tools and 53,190 APIs before, 3,451 tools and 16,464 APIs after. The paper does not report the numbers in between, so the slider interpolates in a straight line. That part is illustrative.
About 31% of the APIs survive. That is a harsh filter, and a good one. Every kept API runs, answers in reasonable time and returns real data. Table 1 of the paper compares this set with earlier datasets.
| Dataset | Tools | APIs | Instances | Real API calls |
|---|---|---|---|---|
| ToolBench (this paper) | 3,451 | 16,464 | 126,486 | 469,585 |
| APIBench | 3 | 1,645 | 17,002 | 0 |
| API-Bank | 53 | 53 | 274 | 568 |
| ToolAlpaca | 400 | 400 | 3,938 | 0 |
| ToolBench (Xu et al.) | 8 | 232 | 2,746 | 3,926 |
Look at the last column. Two of the older datasets never ran a single real call. A model trained on them never saw an error or a messy reply. ToolBench holds 469,585 real calls.
A real reply can be huge. A movie search may return images, cast lists and streaming links for each hit. The reply goes straight into the history from Chapter 1, and the history must fit in the model’s context window, the most text it can read at once. LLaMA-2 starts with 4,096 tokens. A token is a word piece, about three quarters of an English word.
So the authors compress replies. They do it once per API, not once per call. ChatGPT reads the tool documentation, one example reply and three expert-written examples of a compressed reply schema. It then decides which keys can go. At run time the rule is simple. If a reply is longer than 1,024 tokens, remove the unimportant keys. If it is still longer, keep only the first 1,024 tokens.
The second rule is blunt. It cuts the tail, whatever is in it. Try it. Each key has a size in tokens. Switch keys off and see where the cap falls.
The bar is one reply, in order. The dashed line is the 1,024-token cap. Tap a key to keep it or drop it, as the compression schema would.
Illustrative: the key names and their token sizes are invented for a movie-search reply. The 1,024-token cap and the two-step rule (drop keys, then truncate) are the paper’s (Appendix A.2).
With every key on, the reply has 1,320 tokens, and the cap chops off the last keys. Dropping the bulky image block fixes it, and nothing useful is lost. A schema that drops junk beats a blunt cut.
Chapter 3
Turn 16,464 documented APIs into nearly 200,000 realistic user requests, by starting from the APIs and not from the requests
Suppose you must write 200,000 realistic requests that a person might send to an assistant with tools. You sit down and start. “What is the weather?” “What is the weather tomorrow?” After a hundred you are repeating yourself. Worse, for each request you must then hunt for the APIs that could answer it, among thousands.
The paper turns the order around. It does not brainstorm requests and then search for APIs. It first samples a few APIs, then asks ChatGPT: “What would a real person ask that needs these?” The sample guarantees coverage of the whole store. The documentation guarantees that the request is possible.
Each call to ChatGPT carries three things. The first is a general description of the job: write instructions, and list which of the given APIs each one needs. The second is the full documentation of the N sampled APIs, so ChatGPT understands what they do and how they fit together. The third is three seed examples, which are ideal outputs written by human experts. They steer the style through in-context learning, which means the model copies a pattern it sees in the prompt without any weight update.
The authors wrote 12 seed examples for the single-tool setting and 36 for the multi-tool setting. At each call they pick three at random, so the prompts differ from call to call. The output is a list of pairs: an instruction, and the relevant APIs for it.
Real users often need more than one tool. A trip needs flights, weather and a hotel. So the paper builds three kinds of instruction, named I1, I2 and I3.
I1, single-tool. Go through every tool in turn. Sample from the APIs of that one tool. I2, intra-category multi-tool. Choose 2 to 5 tools from one RapidAPI category, and at most 3 APIs from each tool. I3, intra-collection multi-tool. Do the same inside one collection.
Why not mix any tools at random? The authors state it plainly: links among tools in RapidAPI are sparse. A random draw gives a recipe tool, a stock tool and a job-search tool. No natural request needs all three. Test that with the sampler below.
The grid is a toy store with 6 categories of 4 tools. Choose where to sample from, then press Sample. Teal marks the chosen tools.
Illustrative: the categories, tool names and the fixed size of 3 tools are invented. The paper samples 2 to 5 tools from one category or collection and at most 3 APIs from each, and it names the reason: tool links in RapidAPI are sparse. The random draw uses a fixed seed, so the numbers repeat on every visit.
From the whole store, only about 1 draw in 84 lands in one category. That is 6 categories times 4 ways to pick 3 of 4 tools, out of 2,024 ways to pick any 3 of 24 tools. Sampling inside a category makes every draw coherent. ChatGPT can then write a request that uses the tools naturally.
ChatGPT sometimes names a relevant API that was never in the prompt. The authors catch that with one test: every API in Srel must be a member of the sampled set. If it is not, the pair is dropped. This is a plain membership check in code, not another model call.
The final counts are 87,413 instructions of type I1, 84,815 of type I2 and 25,251 of type I3. They add up to 197,479, which the paper calls nearly 200k. The authors judged diversity by human evaluation and by plotting the instructions with the Atlas tool.
pythondef make_instructions(apis, seeds, chatgpt): sub = sample_apis(apis) # I1: one tool; I2/I3: 2-5 tools, same category or collection prompt = task_text() + [doc(a) for a in sub] + random.sample(seeds, 3) pairs = chatgpt(prompt) # [(relevant_apis, instruction), ...] return [(rel, inst) for rel, inst in pairs if set(rel) <= set(sub)] # drop hallucinated APIs
These pairs have two jobs. In Chapter 4 they become the tasks that ChatGPT must solve. In Chapter 6 the relevant APIs become the positive examples for training the retriever.
Chapter 4
Learn why a model that moves in one line gets stuck, and how a tree with a way back finds paths that ReACT never reaches
You have 197,479 instructions and no answers. To train a student you need a solution path for each one: a chain of API calls that ends in a correct answer. ChatGPT must find these paths. So the question is how to make it find them reliably.
Picture a maze with a ball of thread. A walker who can only go forward, and who sticks to the first corridor, is lost at the first dead end. A walker who can pull back along the thread and try the next corridor will usually get out. Chapter 0’s hero showed that difference. Now we build it.
ReACT (reason and act) is the standard loop. At each round the model writes a thought, then an action, then reads the real reply, then writes the next thought. That is exactly the conversation from Chapter 1. It is a single line: one history, one next step.
The authors name two failures from their pilot studies. The first is error propagation. A mistaken action stays in the history, and the model can fall into a loop. It calls the same API wrongly again and again, or it invents an API that does not exist. The second is limited exploration. ReACT looks in one direction only, so it never sees the other branches of the space of actions.
The effect is large. Even GPT-4 often failed to find any valid path for hard instructions, which made annotation inefficient. Measured on ChatGPT, ReACT passes an average of 35.3% of instructions.
The paper’s fix is the depth-first search-based decision tree, DFSDT. Think of the tree as a record of tries. A node is a state: the history so far. An edge is one action the model chose from that state, such as one API call and its reply. A leaf ends a try, either with an answer or with a failure.
At any node the model has two moves. It may proceed along the path that looks promising. Or it may call the function Finish by Giving Up, which abandons this node. The search then backs up one level and asks for a new child.
A fresh child must differ from the old ones, or the model would repeat itself. So the prompt shows the earlier children. The appendix reads: “all previous trails failed” and the model “must generate actions that is different from all of them”.
Why depth first and not breadth first? Annotation is finished the moment one valid path appears. Going deep reaches an answer sooner. Breadth-first search would expand a whole layer before going deeper and would spend far more API calls.
pythondef dfsdt(history, budget, tried=None): tried = tried or [] # children already expanded at this node while budget.left(): act = llm(history, avoid=tried) # diversity prompt lists `tried` tried.append(act) if act.name == "Finish" and act.type == "give_answer": return history + [act] # a valid path: stop at once if act.name == "Finish": # give_up_and_restart: retract return None reply = call_real_api(act); budget.spend() found = dfsdt(history + [act, reply], budget) # go deeper first if found: return found return None # no children left: tell the parent
This sketch is ours, written from the paper’s description. The paper does not publish a cap on children per node here. It measures cost as OpenAI API calls, and so does the budget above.
A textbook DFS would generate several children, rank them, and expand the best first. Asking an LLM to rank n children by pairwise comparison costs about n log2 n calls. For n = 5 that is about 11.6 calls per node. The authors saw that the best child is usually the first one generated. So they skip ranking and expand children in the order they appear: a pre-order traversal.
Two good things follow. If the model never retracts, DFSDT is exactly ReACT and costs the same. And on hard tasks it explores nearly the same nodes as a full DFS. So ReACT is DFSDT with the retract move never used. That is why a model trained on DFSDT data can run either way at test time.
Let each action be good with probability g, otherwise it hits a dead end. Say a task needs D good steps in a row. ReACT has one shot, so it passes with probability gD. At g = 0.6 and D = 3 that is 0.6 × 0.6 × 0.6 = 0.216, or 21.6%. A tree with a few siblings per node gets many more tries on each step.
Each line is the pass rate of one method as the chance g of a good action grows. Drag g to move the marker. Drag the budget to give all three the same number of calls.
Illustrative toy model, not the paper’s data: a task needs 3 good steps in a row, each node allows up to 3 children, and 1,500 simulated tasks (3,000 for the marker) are run per point with a fixed seed. ReACT@N repeats ReACT from scratch until the same budget runs out. The paper’s real averages are in the table below.
Look at the gap between ReACT@N and DFSDT. Repeating from scratch throws away a good first step each time. The tree keeps it and only retries the part that failed.
Table 3 compares the methods on ChatGPT by pass rate. ReACT@N is the fair baseline: it runs ReACT many times until it spends as many calls as DFSDT.
| Method | I1 | I2 | I3 | Average |
|---|---|---|---|---|
| ReACT | 37.8 | 40.6 | 27.6 | 35.3 |
| ReACT@N | 49.4 | 49.4 | 34.6 | 44.5 |
| DFSDT | 58.0 | 70.6 | 62.8 | 63.8 |
Two readings matter. DFSDT wins everywhere. And its gain grows with difficulty: on I3, ReACT@N reaches only 34.6 while DFSDT reaches 62.8. Spending more calls on ReACT does not reach the hard tasks, because the trouble is the shape of the search, not the amount of it. Only passed paths are kept for training, so the same budget also yields more training data.
Chapter 5
Turn 126,486 solved conversations into a 7B model that can call APIs, and stretch its window so long replies fit
Think of a student who watches 126,486 worked solutions and then tries new problems alone. Each solution shows a user request, a tool call, a messy reply, another call, and an answer. After two passes through the pile, the student can write the next step. That is what supervised fine-tuning (SFT) does: the model sees a correct text and learns to predict it token by token.
The student here is LLaMA-2 7B, an open model with 7 billion weights. The teacher is the pile of passed paths from Chapter 4. The result is ToolLLaMA.
The authors train in multi-round conversation mode. They keep the input and output the same as ChatGPT’s. One detail needs a workaround. ChatGPT takes API documentation in a separate “function” field, and no one knows how that field is laid out inside. LLaMA has no such field. So the authors paste the documentation into the prompt as plain text.
One example is therefore a single long text, in this order:
Shapes help here. A batch of 64 examples becomes an integer array of shape [64, T], where T is at most 8,192 tokens. The model returns scores of shape [64, T, 32000], one score for each of the 32,000 tokens in LLaMA-2’s vocabulary at each position.
The settings are in the paper’s Appendix A.3. The learning rate is 5 × 10−5, with a warmup ratio of 4 × 10−2. Warmup means the rate climbs from zero over the first 4% of steps, which keeps early updates gentle. The batch size is 64 and training runs for two epochs. An epoch is one full pass over the data. The authors keep the checkpoint that scores best on a development set.
If each pair were one sequence, two epochs would be about 3,953 optimizer steps (126,486 × 2 ÷ 64). The paper does not state the step count, so take that as a rough guide only.
Here is the problem that Chapter 2 hinted at. The history holds the documentation, every action and every reply. LLaMA-2 can read 4,096 tokens. The paper says that is not enough, because API replies can be very long. Use the device to see where the budget goes.
The bar is the model’s whole input after some rounds of tool use. Change the rounds, the APIs on offer, the window and the reply compression.
Illustrative sizes: 150 tokens of system text, 120 for the instruction, 350 per API document, 120 per action and 2,500 per raw reply. The windows (4,096 and 8,192) and the 1,024-token reply cap are the paper’s.
With 5 APIs and compression on, the window of 4,096 overflows at round 2. The window of 8,192 holds five rounds. Without compression even 8,192 gives out at round 3. So the paper uses both tools: compress replies and double the window.
A transformer needs to know where each token sits. LLaMA-2 does this with rotary position embeddings, which turn the position number into a rotation of the query and key vectors. The model learned from positions 0 to 4,095 only. Position 6,000 is a number it never met, and the attention scores there can become unreliable.
Position interpolation (Chen et al., 2023) avoids this. Divide every position by the ratio r = 8,192 ÷ 4,096 = 2, so all positions land inside the known range. Token 6,000 gets position 3,000. Token 6,001 gets 3,000.5, a fraction the model has not seen but sits between two familiar values. A short fine-tune lets the model adjust. The ToolLLaMA run does exactly this, with a ratio of 2, while it trains on the tool data.
position seen by the model = real position ÷ 2. Token 6,000 → 3,000.0. Token 8,191 → 4,095.5.
One question stays open. The paper says it keeps only passed solution paths. It does not say whether the abandoned branches of the tree appear in the training text. It says only that the model can later be run with either ReACT or DFSDT, because ReACT is DFSDT with no retract.
Chapter 6
Find the five right APIs among 16,464 by comparing meaning, and learn how to score a ranked list with NDCG
A library holds 16,464 books and you need the five that matter for one question. You cannot read them all, and you cannot paste them all into a model’s window. In Chapter 5 the window was already full with five API documents.
Until now the experiments handed the model the right APIs for every task. The paper calls that the oracle setting. A real user will not list the right APIs from a pool of thousands. So the authors train a small model, the API retriever, whose only job is to read an instruction and return the APIs worth showing.
The old way is keyword matching. BM25 scores a document by how many of the query’s words it contains, with a weight that favours rare words. It fails when the words differ. “Which films can I stream tonight?” shares no word with “Search movies and series by title”.
The modern way is an embedding: a model turns a text into a list of numbers, a vector, so that texts with similar meaning get nearby vectors. Think of a map where every sentence has an address, and neighbours mean the same thing. To compare two texts, compare their addresses. The usual measure is cosine similarity, the cosine of the angle between the two vectors. It is 1 when they point the same way.
The paper uses Sentence-BERT with BERT-base as the encoder. The encoder reads a text and returns one vector of 768 numbers. It encodes the instruction and the API document with the same network, then scores their relevance by the similarity of the two vectors.
The data flow is short. Every API document is encoded once, ahead of time: 16,464 × 768 numbers, about 50.6 MB in 32-bit floats (16,464 × 768 × 4 bytes). At run time, encode the instruction into one vector of 768 numbers, take the dot product with all 16,464 stored vectors, and keep the top 5.
Chapter 3 gave us the labels for free. Each instruction came with its relevant APIs. Those are the positives. The authors also sample some other APIs as negatives. Training uses contrastive learning: pull the instruction close to its positives and push it away from its negatives.
Try a toy retriever. The map below is a made-up two-dimensional stand-in for BERT’s 768 dimensions. Pick a question, then compare keyword matching with the embedding.
Pick a question. Green dots are the APIs that truly help. Warm rings are what the retriever returned. Change the retriever and the number of results k.
Illustrative: 17 invented APIs, hand-placed 2-D positions in place of 768-dimensional vectors, four invented questions, and a simple count of shared words in place of full BM25. The NDCG formula is the standard one the paper cites.
How do you grade a list of results where order matters? NDCG (normalised discounted cumulative gain) rewards relevant items and rewards them more near the top. Give each result a relevance of 1 if it helps and 0 if not. The DCG at k adds each relevance divided by log2 of (rank + 1), so rank 1 counts in full and rank 3 counts half.
DCG@k = ∑ reli ÷ log2(i + 1). NDCG@k = DCG@k ÷ IDCG@k, where IDCG is the DCG of the perfect list.
Worked example. There are 3 relevant APIs, and the top 5 results have relevance [1, 0, 1, 0, 0]. DCG@5 = 1 + 1 ÷ log23 × 0 + 1 ÷ log24 = 1 + 0.5 = 1.5. The perfect list is [1, 1, 1, 0, 0], with IDCG = 1 + 0.631 + 0.5 = 2.131. So NDCG@5 = 1.5 ÷ 2.131 = 0.704. A score of 1.0 means a perfect ranking.
Table 2 compares the retriever with BM25 and OpenAI’s text-embedding-ada-002 on the three task types. The numbers are NDCG at 1 and at 5.
| Retriever | I1 @1 / @5 | I2 @1 / @5 | I3 @1 / @5 | Average @1 / @5 |
|---|---|---|---|---|
| BM25 | 18.4 / 19.7 | 12.0 / 11.0 | 25.2 / 20.4 | 18.5 / 17.0 |
| Ada embedding | 57.5 / 58.8 | 36.8 / 30.7 | 54.6 / 46.8 | 49.6 / 45.4 |
| Ours (Sentence-BERT) | 84.2 / 89.7 | 68.2 / 77.9 | 81.7 / 87.1 | 78.0 / 84.9 |
The trained retriever beats Ada by 39.5 points at rank 5 on average, even though Ada is a strong general embedding. Training on the task’s own labels matters. The single-tool tasks (I1) are easier than the multi-tool ones, as the paper notes.
One result is surprising. Feed ToolLLaMA the top 5 retrieved APIs instead of the oracle set, and it does slightly better: an average pass rate of 67.3 and win rate of 63.1, against 66.7 and 60.0. The paper’s explanation is that many true APIs can be replaced by similar ones with better features, and the retriever finds them. It widens the search instead of copying the labels.
Chapter 7
Grade thousands of tool-use runs without a fixed answer key, using two metrics and a ChatGPT judge that votes
You ask three assistants to plan a movie night. One checks three APIs and gives a short list. One checks nine, double-checks a showtime and writes a long answer. One reports that the weather API was down and says so. Who did best?
There is no answer key. The API replies change from day to day, so a stored “correct” reply would go stale. And there are endless valid routes to a good answer. The paper says even human experts often disagree here. One expert prefers the quick path. Another prefers the one that cross-checks.
So the authors build ToolEval, an automatic evaluator that runs on ChatGPT, in the style of AlpacaEval. It has two metrics, and they ask two different questions.
The pass rate is the share of instructions a model completes within a limited budget of calls. It tests executability, which is the minimum for tool use. To rule on one solution path, the judge first asks whether the instruction is solvable. An instruction is unsolvable when every API is irrelevant, or when it carries invalid data such as a false email address. Then it checks how the run ended: with Finish with Final Answer or with Finish by Giving Up.
Each path gets one of three labels: Pass, Fail or Unsure. Try the rules. They come from the paper’s Appendix A.5.
Describe a run, then read the verdict. The same ending can pass or fail, depending on whether the task could be solved.
The rules are the paper’s (Appendix A.5), shortened. The wording of each situation is ours. A single ChatGPT prediction applies these rules, and Pass, Fail and Unsure are the only labels.
Notice rule 1(a). When a model tries every API and nothing helps, giving up is a Pass. The test rewards honest failure over invented success. For an unsolvable task, a false “I have finished” is the one answer that fails.
One ChatGPT prediction can be wrong. So for each solution path the judge makes at least four predictions and takes a majority vote. Voting helps when the errors are independent. Say each vote is flipped with probability p. A majority of n votes is wrong only when more than half flip.
The true verdict is Pass. Set how often one vote flips and how many votes you take, then cast them.
Illustrative: the flip chance is invented and assumes votes err independently, which real LLM votes only roughly do. The paper uses at least four predictions per path and does not report a flip rate.
A pass says only that the job got done. The win rate asks which of two solution paths is better, and it is measured against a reference. In Table 4 the reference is ChatGPT with ReACT. The judge compares two paths only when both passed or both failed, since a pass beats a fail by assumption. It returns win, lose or tie, using six criteria.
Ties need care. Table 4 splits each tie in half between the two sides. Check it with ChatGPT-DFSDT on I1-Inst. The paper’s Table 6 gives win 52.5 and tie 16.0. Then 52.5 + 16.0 ÷ 2 = 60.5, which is the number in Table 4.
The authors checked. They took 300 test instructions for each of four methods and had humans label them. The ChatGPT judge agreed with the humans on 87.1% of pass labels and 80.3% of win labels. That is high, though not perfect. The human experts did not fully agree with one another either.
Our own caution, not a claim of the paper: ChatGPT also wrote the tasks and the training paths, and it is the reference in the win rate. A judge from the same family could favour its own style. The 80% to 87% agreement with humans is the paper’s evidence against that worry.
Finish by Giving Up. What label does ToolEval give?Chapter 8
Read the main table row by row, see how ToolLLaMA does on tools it never met, and note what the paper leaves untested
You now have every piece: real APIs, generated tasks, DFSDT paths, a fine-tuned 7B model, a retriever and a judge. The question for this chapter is simple. Does a small open model trained this way work on tasks it has not seen?
The paper tests three kinds of task. I1 uses one tool, I2 uses several tools from one category, and I3 uses several tools from one collection. It also tests three levels of surprise, because the goal is to handle new APIs from their documentation alone.
Not every pairing exists. I1 has all three levels. I2 has Inst. and Cat. only, since its training tasks already mix tools of one category. I3 has Inst. only. That gives six test sets. In every one, the model receives the oracle (correct) APIs, so the retriever is not in play yet. The baselines are Vicuna, Alpaca, ChatGPT, Text-Davinci-003, GPT-4 and Claude-2, each run with ReACT and with DFSDT.
Explore Table 4 below. Pick a metric and a test set.
Warm bars are ToolLLaMA. Choose pass rate or win rate, then one of the six test sets or the average.
All numbers are the paper’s Table 4, in percent. ChatGPT with ReACT is the reference for win rate, so it has no win rate of its own. Vicuna and Alpaca score 0.0 everywhere and are left out. Only the last row uses the retriever; every other row receives the correct APIs.
Three things stand out. First, DFSDT beats ReACT for every model on average. ChatGPT with DFSDT passes 64.8%, above GPT-4 with ReACT at 57.2%. A better search can matter more than a better model.
Second, ToolLLaMA with DFSDT averages 66.7% pass and 60.0% win. That is above Claude-2 and Text-Davinci-003, close to its teacher ChatGPT (64.8% and 64.3%), and below GPT-4 (71.1% and 70.4%). Third, the surprise rows: ToolLLaMA does well on Tool and Cat. test sets, tools it never trained on. The documentation in the prompt carries the load.
Run the model without DFSDT and it falls to 29.0% pass. The model was trained on DFSDT data, yet only the DFSDT harness around it reveals the skill. That is a clear sign that the search lives in the program and not just in the weights.
All of the above uses ToolBench’s own test split. A fairer test of generalization is a dataset the model never touched. The authors pick APIBench, built for the Gorilla model, with APIs from HuggingFace, TorchHub and TensorHub. They do no extra training. They only present each API as a function to select.
The metrics are the benchmark’s own. AST accuracy checks that the generated call has the same code structure as the correct call. The hallucination rate counts calls to APIs that do not exist. Gorilla is a LLaMA-7B fine-tuned on APIBench’s training data, in a zero-shot setting (ZS) without the API in the prompt and a retrieval-aware setting (RS) with it.
| Method | HuggingFace hallu. / AST | TorchHub hallu. / AST | TensorHub hallu. / AST |
|---|---|---|---|
| ToolLLaMA + our retriever | 10.60 / 16.77 | 15.70 / 51.16 | 6.48 / 40.59 |
| Gorilla-ZS + BM25 | 46.90 / 10.51 | 17.20 / 44.62 | 20.58 / 34.31 |
| Gorilla-RS + BM25 | 6.42 / 15.71 | 5.91 / 50.00 | 2.77 / 41.90 |
| ToolLLaMA + oracle | 8.66 / 88.80 | 14.12 / 85.88 | 7.44 / 88.62 |
| Gorilla-ZS + oracle | 52.88 / 44.36 | 39.25 / 59.14 | 12.99 / 83.21 |
| Gorilla-RS + oracle | 6.97 / 89.27 | 6.99 / 93.01 | 2.04 / 94.16 |
Read it honestly. With retrieval, ToolLLaMA beats both Gorilla settings on AST accuracy for HuggingFace and TorchHub. On TensorHub, Gorilla-RS is a little ahead (41.90 against 40.59). With the oracle, ToolLLaMA beats Gorilla-ZS everywhere, but Gorilla-RS, which trained on APIBench itself, is higher on all three. The fair summary is this: a model that never saw the benchmark comes close to one that trained on it.
Chapter 9
Keep the whole paper on one page: the numbers, the terms, a checklist, the core as code and where to read next
You can now rebuild ToolLLM from memory. Collect real APIs and keep the ones that work. Sample a few and ask ChatGPT for tasks that need them. Solve the tasks with a search tree that can retract. Fine-tune a 7B model on the passed paths. Train a retriever on the same labels. Grade it all with a voting judge. Then test on tools the model has never seen.
ToolLLM teaches an open model to use real APIs by building the lessons with a closed model. ToolBench holds 16,464 filtered RapidAPI APIs, nearly 200,000 generated instructions and 126,486 passed solution paths. The paths come from a depth-first search decision tree that lets the model retract a bad move. LLaMA-2 7B, stretched to an 8,192-token window, becomes ToolLLaMA. A Sentence-BERT retriever picks the top five APIs. ToolEval judges pass rate and win rate with a ChatGPT majority vote. ToolLLaMA nears ChatGPT and generalizes to unseen tools.
| What | Number | Why it matters |
|---|---|---|
| Crawl, then filter | 10,853 tools and 53,190 APIs, then 3,451 and 16,464 | Only about 31% of APIs are reliable |
| RapidAPI structure | 49 categories, 500+ collections | Used to group related tools |
| Instructions | 87,413 + 84,815 + 25,251 = 197,479 (I1, I2, I3) | Single-tool and multi-tool coverage |
| Seed examples | 12 single-tool, 36 multi-tool, 3 per prompt | The only human-written data |
| Solution paths kept | 126,486; 469,585 real calls; 4.0 reasoning traces on average | Real replies, errors included |
| Reply cap | 1,024 tokens (drop keys, then truncate) | Keeps the history inside the window |
| Model and window | LLaMA-2 7B, 4,096 to 8,192 by position interpolation (ratio 2) | Long replies need a longer window |
| Training | lr 5e-5, warmup 0.04, batch 64, 2 epochs | Plain SFT, nothing exotic |
| Search, Table 3 average | ReACT 35.3; ReACT@N 44.5; DFSDT 63.8 | A tree beats repeated tries |
| Retriever, NDCG@5 average | BM25 17.0; Ada 45.4; ours 84.9 | Trained on task labels wins |
| ToolEval vs humans | 87.1% pass, 80.3% win agreement | The judge is credible, not perfect |
| Table 4 average, DFSDT | ToolLLaMA 66.7 pass, 60.0 win; ChatGPT 64.8, 64.3; GPT-4 71.1, 70.4 | A 7B model near its teacher |
| ToolLLaMA with retriever | 67.3 pass, 63.1 win | Retrieved APIs can beat labelled ones |
| Vicuna and Alpaca | 0.0 pass and win | Chat tuning gives no tool skill |
| APIBench TorchHub, AST | ToolLLaMA + retriever 51.16; Gorilla-ZS 44.62; Gorilla-RS 50.00 | Unseen benchmark, no extra training |
| Term | Meaning in this paper |
|---|---|
| API, tool | One callable door; a provider’s bundle of doors |
| Instruction tuning | Fine-tuning on pairs of instruction and good answer |
| ReACT | Thought, action, observation in one line, with no retract |
| DFSDT | Depth-first search tree of tries with a give-up move |
| ToolBench, ToolLLaMA, ToolEval | The dataset, the fine-tuned model, the evaluator |
| Oracle APIs | The correct APIs, handed to the model for a test |
| Pass rate, win rate | Finished the job; better than a reference path |
| NDCG@k | Ranking score that favours relevant items near the top |
| Position interpolation | Divide positions by a ratio so a longer window uses known ones |
This sketch ties the chapters together. The helper functions stand for the pieces built above. It is our summary of the paper’s pipeline, not the authors’ code. Theirs is at the ToolBench repository.
python# Phase 1: API collection (Ch 2) apis = [a for a in crawl_rapidapi() if runs(a) and good_example_reply(a)] # 53,190 -> 16,464 # Phase 2: instruction generation (Ch 3) pairs = [] for mode in ("I1", "I2", "I3"): for sub in sample_apis(apis, mode): # I2/I3: 2-5 tools, same category or collection pairs += make_instructions(sub, seeds, chatgpt) # keeps only rel <= sub; ~197k pairs # Phase 3: solution paths with DFSDT (Ch 4) data = [] for rel, inst in pairs: path = dfsdt([system(rel), user(inst)], Budget(calls)) if path: data.append((rel, inst, path)) # keep passed paths only: 126,486 # Models (Ch 5, 6) tool_llama = sft(llama2_7b, data, ctx=8192, pi_ratio=2, lr=5e-5, batch=64, epochs=2) retriever = train_contrastive(sbert_base, [(inst, rel) for rel, inst in pairs]) # Inference def answer(inst): top5 = retriever.top_k(inst, apis, 5) # Ch 6 return dfsdt([system(top5), user(inst)], Budget(calls), llm=tool_llama)
Lecture 5 treats the harness as the thing worth engineering. ToolLLM is a sharp example. DFSDT is a harness change, and it is worth more than a bigger model in Table 4. The data pipeline is a second harness, one that writes lessons for another model.
The loop in Chapter 1 is the loop of the ReACT paper. The retract move extends the idea of Reflexion. The self-taught skill of calling tools also appears in Toolformer. The paper also lists the concurrent tree-of-thoughts work, and says its own target, an unbounded space of actions, differs from the small puzzles that tree-of-thoughts solves.
ToolLLM is the work of Yujia Qin, Shihao Liang, Yining Ye, Kunlun Zhu, Lan Yan, Yaxi Lu, Yankai Lin, Xin Cong, Xiangru Tang, Bill Qian, Sihan Zhao, Lauren Hong, Runchu Tian, Ruobing Xie, Jie Zhou, Mark Gerstein, Dahai Li, Zhiyuan Liu and Maosong Sun, from Tsinghua University, ModelBest, Renmin University of China, Yale University, WeChat AI at Tencent and Zhihu. Read the original at arXiv 2307.16789 (version 2, 3 October 2023). Code, data and models are at github.com/OpenBMB/ToolBench. This lesson re-teaches the paper for MIT MAS.S62 AI4AI. Any mistake in the teaching is ours.
Now press Present or Teach and explain the pipeline out loud: why filter, why sample APIs first, why a tree beats a line, how the window grows, how NDCG scores a list, and why the judge votes. Or go back to the search tree at the top and run ReACT and DFSDT again. You will now know what each node costs.