tutorials
Choose and force tool calls with the OpenAI API
Overview
Suppose you ask a model for a number from a paper. You could put the whole table in the prompt, or give the model a way to look up one row. With the OpenAI Chat Completions API, your code decides which tools to offer and whether the model gets to choose when to use them. The model proposes a function call. Your code executes it and sends back the result.
In this tutorial, we’ll use Paper MCP, a small toy library for working with research papers. It can search the text of a PDF you’ve imported, read a page, and crop a region you select. We’ll use it to see what the model asks for and what evidence the tool gives back.
We'll try this with Gemma 4 through the course gateway. As you work through the tutorial, keep the following two questions in mind:
- Can the model choose a useful tool and supply the right arguments?
- Once it has the result, can it use that evidence to answer the question?
Outcomes
After working through the examples, you should be able to …
- choose which functions to offer in a Chat Completions request
- let the model decide, require a call, or force a particular function
- execute a function locally and return its result using the matching call ID
- use logs to check the tool choice, its arguments, the returned evidence, and the final answer separately
From supplying text to calling a tool
In our last tutorial, we supplied paper text in a message before asking the model a question. Here, the first request provides a question and descriptions of available tools. If the model requests a tool, your script retrieves the evidence and adds it to the conversation before asking for an answer.
We’ll first run a complete program, then adapt it to investigate a question about your own paper. Along the way, we’ll walk through code (in Python) that makes this exchange work.
Start Paper MCP
There are many ways to give language models tools. One standard is the Model Context Protocol, or MCP. It gives an application a common way to discover and call tools provided by a server. Here, Paper MCP runs on your computer and supplies tools for working with PDFs. Your code will talk to two services. It sends prompts and function declarations to the course Model Gateway using Chat Completions. When the model requests a function, the client (the code you're running on your computer) calls Paper MCP and sends the result back to the model.
We’ll use Scientific Discovery as Link Prediction in Influence and Citation Graphs as our paper for the examples that follow. This academic paper asks whether graphs of scientific findings and citations can help predict which connections researchers will report later.
The code that calls the Model Gateway is your client. In this tutorial, you’ll use a provided MCP server to search and read your local PDF. Your client runs the tools requested by the model through that server and sends the results back to the model.
| Component | What it does in this example |
|---|---|
Your Python client (paper-tool-choice) |
Sends the question and tool descriptions, checks and executes requested calls, and returns the evidence to the model. |
| Course gateway and model | Receive the conversation, propose tool calls, and generate an answer after receiving the evidence. |
| Local Paper MCP server | Executes PDF searches and page reads and returns their results to your client. |
Part 1: Run the provided example
First, we’ll run the example without changing its code. You’ll use the supplied paper and question, inspect the tool calls, and check the model’s answer. In the second part of this tutorial, you’ll adapt the example to investigate a question about your own paper.
Set up a local Python environment
We’ll use local Python throughout this tutorial. You need Python 3.12 or newer. If you already use conda or micromamba†, activate an environment with that Python version and skip the two .venv lines below.
You’re welcome to use your preferred environment. The commands below use Bash syntax, so adapt them as needed for your shell. Keep using the same terminal so your environment settings remain available.
Before the install step below, check your Python environment†.
# Clone the course repository over SSH and enter it.
git clone ssh://git@git.hlt.parsertongue.org/teaching/paper-mcp.git
cd paper-mcp
# Create and activate a Python environment for this checkout.
python -m venv .venv
source .venv/bin/activate
# Install Paper MCP and its command line tools in editable mode.
# Editable mode lets us change code in the cloned repo
# and rerun the example without reinstalling,
# which we'll do later in this tutorial.
python -m pip install -e .
# Make directories for the example paper and saved traces.
mkdir -p papers traces
# Download the example paper.
curl --fail --location https://aclanthology.org/W18-1701.pdf \
--output papers/W18-1701.pdf
# Import the paper and print its document ID.
pdf-library import papers/W18-1701.pdf
The -e option installs the package in editable mode. Python uses the code in your checkout, so you can save code changes and rerun the commands without reinstalling.
Copy the printed document_id for the next step.
Run the complete example
Stay in the root directory of your paper-mcp clone with your Python environment active.
Installation registers a terminal command named paper-tool-choice in your active Python environment. Running it calls main() in src/pdf_mcp/tool_choice.py, as configured in the repository's pyproject.toml. You are running that Python program through its command name.
The example starts Paper MCP for you as a local subprocess†.
The program asks: On PDF page 5, what precision does the Full model row report in Table 5? Each command below starts a fresh conversation with that same question. Only the first request's tool policy changes. When a tool is used, the program prints the requested tool and arguments, the returned evidence, and the final answer.
First, set the document ID and gateway connection details. The export commands make these values available to the Python program. They do not send a model request.
export DOCUMENT_ID="paste the document_id from pdf-library import here"
# Copy the gateway base URL, project API key, and model ID from your project.
export GATEWAY_BASE_URL="paste the gateway base URL here"
export GATEWAY_API_KEY="paste your project API key here"
export GATEWAY_MODEL="gemma4-12b"
The gateway base URL should include /v1. The project must allow search_pdf and read_pdf_pages. Follow Model Gateway basics to find the project settings.
Now run the four conditions, one command at a time. Each command saves a trace† so you can inspect what the model received and returned.
# No tools: ask the model without giving it a way to retrieve the paper.
paper-tool-choice "$DOCUMENT_ID" none --trace traces/example-none.jsonl
# Let the model decide whether to request one of the two tools.
paper-tool-choice "$DOCUMENT_ID" auto --trace traces/example-auto.jsonl
# Require a tool call; the model chooses which offered function to request.
paper-tool-choice "$DOCUMENT_ID" required --trace traces/example-required.jsonl
# Require read_pdf_pages; the model still supplies the page arguments.
paper-tool-choice "$DOCUMENT_ID" read_pdf_pages --trace traces/example-forced.jsonl
If you repeat a run, choose a new trace filename so you keep the earlier result.
What to compare in the output
For each run, check three things:
- The call: did the model request a tool? For a page read, look for
read_pdf_pages, your document ID, andstart_page=5andend_page=5. - The evidence: does the printed tool result contain Table 5 and enough information to associate values with column headings?
- The answer: does the model report the precision correctly? Compare with the original table: precision is 0.528; 0.268 is F1.
The three tool-enabled runs may make the same call and produce the same answer. Different tool policies can still produce the same result. For example, the model might choose read_pdf_pages under auto and request the same pages when that function is required. If that happens, check the traces to see whether the model received the same evidence.
What Gemma 4 returned
Here is what happened when I ran the experiment with Gemma 4 12B (the google/gemma-4-12B-it-qat-w4a16-ct checkpoint, listed as gemma4-12b in the course gateway). I included the document ID in the prompt and asked Gemma for the precision on PDF page 5.
| First request | What Gemma did | Final answer |
|---|---|---|
| No tools | Asked me to upload the PDF or provide the table text or image | Gave no value |
auto |
Requested read_pdf_pages for PDF page 5 |
0.268 |
required |
Requested read_pdf_pages for PDF page 5 |
0.268 |
Forced read_pdf_pages |
Requested read_pdf_pages for PDF page 5 |
0.268 |
In another run without tools, it invented a different Table 5!
Check the answer separately from the tool call. Paper MCP returned the requested page in all three tool runs. 0.268 is the F1 score. The requested precision is 0.528.
PDF text extraction can recover the numbers while making it harder to tell which column each one belongs to. On the original Table 5 page, you can see 0.268 under F1 and 0.528 under Precision. The optional vision tutorial shows what a crop can preserve.
In a separate request, I appended the following line to the same question. I transcribed it from the table and put each column name next to its value. Gemma returned 0.528. This comparison changes both the amount of text and how the values are labeled.
Full model: F1=0.268, Precision=0.528, Recall=0.176.
Why bother?
Yes, I could read the precision straight from the table. The point of giving the model a row I labeled by hand was to see whether it could answer once the column names and values were explicitly paired. That gives us one way to investigate where the failure happened and what might help. The goal here is to understand how, where, and why models fail. You can decide for yourself whether using a model makes sense for a particular task.
Gemma is a multimodal LLM. It can take both text and images as input. What if we gave it an image of the table? In two trials with the same question, Gemma gave 0.268 with the extracted page text alone and 0.528 when I added a crop of the table. The crop alone also gave 0.528 in both trials. For the brave and curious, the optional vision tutorial walks through that comparison.
Part 2: Adapt the example to investigate your paper
Pick one question about your paper with an answer you can check. Keep the question and model the same across two runs, and change something about the evidence the model receives. Use the comparison to investigate what evidence helps the model answer your question.
Try a question from your own paper
Start by changing the question while keeping the supplied client and its two page lookup tools. You can do this with command line options before changing any Python.
Copy your paper to papers/my-paper.pdf, import it, and set DOCUMENT_ID to the new ID:
pdf-library import papers/my-paper.pdf
export DOCUMENT_ID="paste your own paper's document_id here"
Then ask your question and save a trace. The --question option replaces the built-in Table 5 question.
paper-tool-choice "$DOCUMENT_ID" auto \
--question "Replace this with your question about the paper." \
--trace traces/my-paper-auto.jsonl
Open traces/my-paper-auto.jsonl to inspect the question, tool calls, returned evidence, and answer. Check the answer against the paper. What evidence did the model receive, and what might still help?
Changing a tool mode may return the same evidence. Use the trace to establish what actually changed in your comparison. You can also provide evidence directly, as described in the assignment prompt.
Walk through the Python client
The model requests a tool. Your client checks and executes that request, then sends the result back so that the model can answer. In this section, we’ll follow those steps through one page read.
We’ll follow the read_pdf_pages run from Part 1. In that run, we asked for the precision in the Full model row of Table 5 on PDF page 5 and required the model to request read_pdf_pages. Use its saved trace, traces/example-forced.jsonl, as you read.
Keep src/pdf_mcp/tool_choice.py open alongside this section. The Python blocks below are excerpts from that file, with its variable names unchanged. We’ll concentrate on run_exchange(), where client is the gateway connection and paper_mcp is the connection to the local MCP server. The program establishes both connections before calling this function.
1. Construct the first request
First, the client imports the declarations for its two page lookup tools†:
from .tools import PAGE_LOOKUP_TOOLS
PAGE_LOOKUP_TOOLS is a list of descriptions for search_pdf and read_pdf_pages, including their names and arguments. Importing those descriptions does not run either tool.
Here is what the list contains, shown as JSON. Each entry is a tool declaration that tells the model what it can request:
[
{
"type": "function",
"function": {
"name": "search_pdf",
"description": "Find passages in one imported PDF.",
"parameters": {
"additionalProperties": false,
"properties": {
"document_id": {
"maxLength": 64,
"minLength": 64,
"title": "Document Id",
"type": "string"
},
"query": {
"maxLength": 500,
"minLength": 1,
"title": "Query",
"type": "string"
},
"limit": {
"default": 5,
"maximum": 10,
"minimum": 1,
"title": "Limit",
"type": "integer"
}
},
"required": [
"document_id",
"query"
],
"type": "object"
}
}
},
{
"type": "function",
"function": {
"name": "read_pdf_pages",
"description": "Read extracted text from physical PDF pages.",
"parameters": {
"additionalProperties": false,
"properties": {
"document_id": {
"maxLength": 64,
"minLength": 64,
"title": "Document Id",
"type": "string"
},
"start_page": {
"minimum": 1,
"title": "Start Page",
"type": "integer"
},
"end_page": {
"minimum": 1,
"title": "End Page",
"type": "integer"
}
},
"required": [
"document_id",
"start_page",
"end_page"
],
"type": "object"
}
}
}
]
In each declaration, function.name identifies the tool, and function.description explains what it does. function.parameters describes the arguments as a JSON Schema†. Its properties specify the accepted fields, their types, and their constraints. The required list identifies which arguments must be supplied. For example, read_pdf_pages requires a document ID and two integer page bounds. The model supplies those argument values when it requests a call.
At the start of run_exchange(), the client constructs the request options and the initial conversation:
request = {"model": model, "tools": PAGE_LOOKUP_TOOLS, "max_tokens": 2048}
messages = [
{"role": "user", "content": f"{question} Imported document ID: {document_id}"}
]
first_request = request.copy()
if choice == "none":
first_request.pop("tools")
record("request", **first_request, messages=messages.copy(), tool_choice=choice)
question is the question supplied to the program. For the Part 1 example, it asks for the precision in the Full model row of Table 5 on PDF page 5. document_id is the ID printed when you imported the paper. The messages list puts both into one user message. It does not contain the paper text yet.
In this example, choice is a dictionary that names read_pdf_pages, as described under tool policies below. The if choice == "none" branch is skipped. In the no tools baseline, that branch removes the declarations from the first request.
record() writes an event to the trace file when tracing is enabled. The last line in the excerpt saves the first request before it is sent to the gateway.
Open your trace in your preferred text editor and find the request event. Check its question, imported document ID, tool declarations, and tool_choice. Nothing has been retrieved from the paper at this point.
2. Send the request and read the model’s proposed call
The client uses await† to wait for the gateway’s reply, then selects the first completion choice:
first = (
await client.chat.completions.create(
**first_request, messages=messages, tool_choice=choice
)
).choices[0]
**first_request passes the options from the dictionary as keyword arguments†. first is one completion choice. Its message contains the model’s reply, which the client records in the first completion event.
After checking that the turn completed, the client reads any requested calls:
calls = first.message.tool_calls or []
Here is an illustrative call for the expected page. Your call ID will differ. Use the document ID printed by your own import:
{
"id": "call_example",
"type": "function",
"function": {
"name": "read_pdf_pages",
"arguments": "{\"document_id\":\"<imported document ID>\",\"start_page\":5,\"end_page\":5}"
}
}
The arguments arrive as a JSON string. The client will convert the JSON string into a Python dictionary before running the tool. Both page bounds are 5 because the range includes its endpoints. A forced tool choice fixes the function name. The model still has to supply the correct document ID and page arguments.
Next, find the first completion event and its message.tool_calls. Read the function name, arguments, and call ID there. This event records a proposed call, not the result of reading the PDF.
3. Save the call and execute it through Paper MCP
Before adding a tool result, the client adds the assistant message that requested it† to the conversation:
messages.append(
first.message.model_dump(
include={"role", "content", "tool_calls"}, exclude_none=True
)
)
model_dump() converts that message to a Python dictionary.
The client then checks each requested function and converts its arguments from a JSON string into a Python dictionary. This excerpt includes the call to the existing execute() function:
offered = {tool["function"]["name"] for tool in PAGE_LOOKUP_TOOLS}
for call in calls:
if call.type != "function" or not call.id:
raise SystemExit("Invalid tool call.")
if call.function.name not in offered:
raise SystemExit("Model requested a tool outside the selected subset.")
arguments = json.loads(call.function.arguments)
if not isinstance(arguments, dict):
raise SystemExit("Tool arguments must be a JSON object.")
print(call.function.name, arguments)
result = await execute(paper_mcp, document_id, call.function.name, arguments)
content = tool_content(result)
execute() is defined earlier in the same file. It checks that the requested document ID matches the imported paper. For read_pdf_pages, it also requires the same positive integer for start_page and end_page. It then calls paper_mcp.call_tool(...) to retrieve that page through the local MCP server.
In your trace, find tool_result with the same call ID as the proposed call. result records what the tool returned. content records what the client will send to the model. Usually that is the same information serialized as JSON.
4. Append the result to the conversation
Still inside the loop, the client adds the returned content as a tool message†:
messages.append({"role": "tool", "tool_call_id": call.id, "content": content})
The conversation now contains the original question, the assistant’s tool call, and the corresponding tool result. The evidence has been added locally. It has not yet been sent back to the model.
In your trace, the tool_result event records the content used in this message. The next event, follow_up, marks the client’s preparation of another gateway request. The program sends the evidence once, in the tool message’s content field.
5. Send the evidence and read the answer
The client sends the updated conversation to the gateway and selects the first completion choice again:
final = (
await client.chat.completions.create(
**request, messages=messages, tool_choice="none"
)
).choices[0]
request still contains the tool declarations†. On this turn, tool_choice="none" disables another tool call. The model can now use the returned evidence in its reply, though it might still misread the table or find the evidence insufficient.
The client records the final completion, checks that it finished, and returns final.message.content for the program to print.
In your trace, find the last completion event and read its answer. Compare that answer with both the returned evidence and the original table. Retrieving page 5 and interpreting its precision column correctly are separate checks.
Compare the tool policies
Forcing a particular function isn’t the only way to control tool use. We can also let the model decide whether a tool would help, require a call without naming the function, or disable tool calls.
Return to the four runs from Part 1. They use the same exchange code, with a different choice for the first request:
tool_choice |
What the first request allows |
|---|---|
"none" |
The model replies without calling a tool. The client leaves tool declarations out of this first request. |
"auto" |
The model can reply directly or call an offered tool. |
"required" |
The model must call at least one offered tool. It chooses the function and arguments. |
{"type": "function", "function": {"name": "read_pdf_pages"}} |
The model must request read_pdf_pages. It still supplies the document and page arguments. |
The program converts the command line option read_pdf_pages into the dictionary shown in the last row before calling run_exchange(). The Chat Completions API reference describes these options under tool_choice.
If the first reply has no tool call, the client returns its text without executing a tool or sending a second request. If a tool runs, the second request uses none in all three tool conditions. Compare the first request and completion events to see what the different policies changed. Then check the evidence and final answer separately.
The library also provides CITATION_TOOLS, IMAGE_TOOLS, and ALL_TOOLS. Keep PAGE_LOOKUP_TOOLS for this exchange. Offering another function would also require the client to check and execute it. The existing execute() function handles only the two page lookup tools.
Modify and rerun the client
If you’d like to change the client’s behavior, edit src/pdf_mcp/tool_choice.py in your local checkout. You might change how the question is presented or which tools are offered. Check that the client can validate and execute any tool you add.
Save your changes, then run paper-tool-choice again with a new trace filename and inspect what changed. Editable mode lets the command use your updated Python code without another install.
If you change package metadata in pyproject.toml, such as dependencies or command entry points, run python -m pip install -e . again.
You can also investigate evidence changes using the supplied client or by providing evidence directly.
Try the same idea with paper evidence
The lookup example gives us a small way to inspect tool calling. The examples below show other things a tool could provide. For example, Paper MCP can search an imported PDF or return a page's extracted text. A client can expose either operation to our selected model as a function and record which evidence came back. The Paper MCP walkthrough shows how to inspect those results.
Find the evidence for a claim
Let’s ask how the authors evaluated their predictions. What did the all positive baseline assume about links before and after the 2012 cutoff?
Try searching for backtesting with search_pdf. In my run, the search returned several pages, including page 4. Follow that hit with read_pdf_pages to get the surrounding text. Then check the caption of Table 4 on PDF page 4.
What would count as a correct answer? The baseline predicts that the link from A to C will be discovered after the cutoff if both the link from A to B and the link from B to C already existed before it. An answer that only gives the year or says “the baseline predicts all links” leaves out which links qualify. If the tool result contains a general discussion of backtesting, try giving the model the Table 4 caption. If you use the CLI in the repository walkthrough, you can check what the model received in its trace.
Check whether the paper supports a claim
Suppose the model says AdaBoost had the highest recall of all the systems in Table 4. Check the Recall column and pay attention to which rows the claim covers. AdaBoost reports 0.178. The neural network reports 0.206, and the all positive baseline reports 1.0. AdaBoost does lead on P@10 and MAP in that table. A claim can sound plausible when it borrows a result from the wrong column.
Next steps
Use your traces to explain what the comparison showed. Include the relevant request and response excerpts, check both answers against the paper, and identify specific evidence that might help.
If you’re using this example for the Paper Review assignment, the Paper Review resources connect these steps to Part 2. See Class Maestro for the current prompt and rubric.
If you’d like to explore how to use a model’s vision capabilities, the optional Test image evidence from a paper tutorial shows how to use a table crop as evidence.