Sub topic 3
Controlling LLM Tool Use
Assume you know Python, JSON, chat message roles, and how to call an LLM API. The model proposes tool calls; your application decides whether to execute them.
Choosing Which Tools Are Used
Tool choice usually has three modes:
- Automatic: the model may answer directly or select a suitable tool.
- Forced: the request requires a particular tool.
- Disabled: the model must produce text without tools.
Use automatic choice for general assistants. Force a tool when an operation must happen, such as looking up an account before displaying its status. Disable tools for tasks such as summarization.
A forced choice does not grant permission. Your application must still validate the call and enforce access rules.
Handling Several Calls
A model can request several independent calls in one response. Run them concurrently when the operations are independent, then return one result for each call ID.
from concurrent.futures import ThreadPoolExecutor
def run_calls(calls, run_tool):
with ThreadPoolExecutor(max_workers=len(calls)) as pool:
results = list(pool.map(run_tool, calls))
return [
{"role": "tool", "tool_call_id": call["id"], "content": result}
for call, result in zip(calls, results)
]Do not parallelize calls with ordering or data dependencies.
Designing Usable and Safe Tools
Give each tool one clear purpose. Use names such as get_weather, not handle_request. Descriptions should explain when to use the tool and what each argument means. Keep schemas narrow with required fields, enums, length limits, and additionalProperties: false.
Security and Limits
Treat tool output as untrusted input. A web page or document can contain prompt injection that tells the model to ignore its instructions. The application must enforce permissions independently of the model.
Expose small, least-privilege tools. Require confirmation for irreversible actions, such as sending money or deleting data. Set a maximum number of loop steps and timeouts. These limits control runaway calls, cost, and latency.
Structured Output and Evaluation
Tool calling is for requesting an external action or data lookup. Structured output is for making the model's answer match a schema without executing a function. Choose tool calling when code must perform work; choose structured output when you only need validated data.
Test with cases that check tool selection, arguments, refusal, errors, multiple calls, and injection attempts. Record whether the model chose the correct tool, supplied valid arguments, and recovered from failures.
Exercise
When should an application force a tool instead of allowing automatic tool choice?
Show answer
Force it when the workflow requires that specific operation, while still validating arguments and enforcing permissions in application code.